Search code examples
bashshellshposix

Shell script source on non-existing file terminates the script


Consider Below:

#!/bin/sh

# GNU bash, version 4.1.2(1)-release
echo "Start"
cd /path/does/not/exists # this does not terminate
source /path/does/not/exists

echo $?
echo "End"

Result:

Start
./test.sh: line 6: /path/does/not/exists: No such file or directory

Why none of the echos print anything and script terminates? why only source error is caught without setting explicit set -e and terminates the script?


Solution

  • When running in posix mode, bash will abort if the file named as the argument to . (aka source) does not exist. See: https://pubs.opengroup.org/onlinepubs/9699919799/utilities/V3_chap02.html#tag_18_18

    If no readable file is found, a non-interactive shell shall abort; an interactive shell shall write a diagnostic message to standard error, but this condition shall not be considered a syntax error.

    Since you have used #!/bin/sh as the shebang, bash is running in posix mode. From the bash manpage:

    If bash is invoked with the name sh, it tries to mimic the startup behavior of historical versions of sh as closely as possible, while conforming to the POSIX standard as well.