Shell 不存在文件上的脚本源终止脚本
Shell script source on non-existing file terminates the script
考虑以下:
#!/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
中的 none 打印任何内容并且脚本终止?为什么只捕获 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.
考虑以下:
#!/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
中的 none 打印任何内容并且脚本终止?为什么只捕获 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.