bash - 不存在文件上的 Shell 脚本源终止脚本

标签 bash shell sh posix

考虑以下:

#!/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/

相关文章:

bash - Awk 搜索并附加来自其他 csv 文件的匹配名称

linux - bash:kill $$ 不起作用?

linux - 在 Linux 中使用 Bash 列出带空格的目录

shell - 批量检测系统是 32 位还是 64 位

bash - 以下片段是否有效的 Bourne shell 代码?

bash - 如何使用awk删除重复的逗号分隔字符串

Bash - 根据索引列表中未列出的索引从文件中提取行

Python 将所有其他内容压缩到同一文件中

unix - 你能告诉我以下代码的错误吗?

bash - 如何在 shell 脚本中提取字符串的前两个字符?