不存在的文件上的Shell脚本源终止脚本
考虑以下:
#!/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
为什么echos都不打印任何内容并且脚本终止?为什么只source捕获错误而不设置显式set -e并终止脚本?
回答
在 posix 模式下运行时,bash如果命名为.(aka source)的参数的文件不存在,则将中止。请参阅:https : //pubs.opengroup.org/onlinepubs/9699919799/utilities/V3_chap02.html#tag_18_18
如果没有找到可读文件,非交互式 shell 将中止;交互式 shell 应将诊断消息写入标准错误,但这种情况不应被视为语法错误。
由于您已用作#!/bin/shshebang,因此 bash以 posix mode 运行。从bash联机帮助页:
如果使用名称 sh 调用 bash,它会尝试尽可能模仿 sh 历史版本的启动行为,同时也符合 POSIX 标准。