考虑以下:
#!/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"
结果:
Start
./test.sh: line 6: /path/does/not/exists: No such file or directory
为什么没有一个 echo
打印任何内容并且脚本终止?为什么只捕获 source
错误而不设置显式 set -e
并终止脚本?
最佳答案
在 posix 模式下运行时,如果作为 .
的参数命名的文件(又名 source
)不存在,bash
将中止。请参阅: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.
因为您使用了 #!/bin/sh
作为 shebang,bash 是 running in posix mode .来自 bash
联机帮助页:
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.
关于bash - 不存在文件上的 Shell 脚本源终止脚本,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/67844511/