Reputation: 1277
I have two scripts:
fail_def.sh:
#!/bin/bash -eu
function fail() {
echo -e "$(error "$@")"
exit 1
}
bla.sh:
#!/bin/bash -eu
fail "test"
After source fail_def.sh
, I can use the fail command without any problems in the terminal. However, when I call bla.sh
, I always get line 2: fail: command not found
.
It doesn't matter whether I call it via ./bla.sh
or bash bla.sh
or bash ./bla.sh
, the error remains.
Adding source fail_def.sh
to the beginning of bla.sh
solves the problem, but I'd like to avoid that.
I'm working on an Ubuntu docker container running on a Mac, in case that is relevant.
I tried to google that problem and found some similar problems, but most of them seem to be connected to either not sourcing the file or mixing up different shell implementations, neither of which seems to be the case here.
What do I have to do to get the fail command to work inside the script?
Upvotes: 3
Views: 1716
Reputation: 85875
It is expected!
The shell runs the script run with an she-bang separator always as a separate process and hence on a different shell namespace. The new shell in which your script runs does not have the function source'd.
For debugging such information, add a line echo $BASHPID
which prints the process id of the current bash process on the bla.sh
script after the line #!/bin/bash -eu
and a test result produced
$ echo $BASHPID
11700
$ bash bla.sh
6788
fail.sh: line 3: fail: command not found
They scripts you have run on separate process where the imported functions are not shared between. One of the ways would be to your own error handling on the second script and by source-ing the second script. On the second script
$ cat fail.sh
echo $BASHPID
set -e
fail "test"
set +e
Now running it
$ source fail.sh
11700
11700
bash: error: command not found
which is obvious as error
is not a shell built-in which is available. Observe the process id's same on the above case.
Upvotes: 2