Skip to content

BASH_SOURCE[0] is empty when running bash /path/script.sh #942

@chaliy

Description

@chaliy

Summary

When executing a script via bash /path/script.sh, BASH_SOURCE[0] is empty. In real bash, BASH_SOURCE[0] equals the script file path.

Reproduction

# FAIL — BASH_SOURCE empty in bash /script
echo 'echo "source: ${BASH_SOURCE[0]}"' > /tmp/test_source.sh
bash /tmp/test_source.sh
# expected: source: /tmp/test_source.sh
# actual:   source:

# FAIL — dirname pattern breaks
echo 'DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"; echo "dir: $DIR"' > /tmp/test_dir.sh
bash /tmp/test_dir.sh
# expected: dir: /tmp
# actual:   (error or empty — dirname of empty string)

# PASS — source (.) does populate BASH_SOURCE
echo 'echo "source: ${BASH_SOURCE[0]}"' > /tmp/test_sourced.sh
source /tmp/test_sourced.sh
# expected: source: /tmp/test_sourced.sh

Spec tests to add

Add to crates/bashkit/tests/spec_cases/bash/:

### bash_source_in_executed_script
# BASH_SOURCE[0] should equal script path when run via bash
echo 'echo "${BASH_SOURCE[0]}"' > /tmp/bsrc_test.sh
bash /tmp/bsrc_test.sh
### expect
/tmp/bsrc_test.sh
### end

### bash_source_dirname_pattern
# Common pattern: find script's own directory
echo 'echo "$(dirname "${BASH_SOURCE[0]}")"' > /tmp/bsrc_dir.sh
bash /tmp/bsrc_dir.sh
### expect
/tmp
### end

### bash_source_in_sourced_script
# BASH_SOURCE[0] in sourced scripts (verify no regression)
echo 'echo "${BASH_SOURCE[0]}"' > /tmp/bsrc_sourced.sh
source /tmp/bsrc_sourced.sh
### expect
/tmp/bsrc_sourced.sh
### end

Where to fix

execute_shell() in crates/bashkit/src/interpreter/mod.rs (around lines 2559-2673). When a script file path is provided, push it onto bash_source_stack (or call update_bash_source()) before executing the script content. Pop it after execution completes.

Search for existing bash_source handling in the source builtin implementation for reference — it already does this correctly.

Real-world impact

Scripts that use BASH_SOURCE[0] to find their own location (a very common pattern) will break. The wedow/harness uses this in bin/harness line 6 to discover HARNESS_ROOT, and in spec/run to locate test files.

Metadata

Metadata

Assignees

No one assigned

    Labels

    bugSomething isn't working

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions