代码之家  ›  专栏  ›  技术社区  ›  pmoubed

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

  •  1
  • pmoubed  · 技术社区  · 4 年前

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

    1 回复  |  直到 4 年前
        1
  •  5
  •   William Pursell    4 年前

    在posix模式下运行时, bash 如果文件名为 . (又名 source )不存在。请参见: https://pubs.opengroup.org/onlinepubs/9699919799/utilities/V3_chap02.html#tag_18_18

    如果找不到可读文件,非交互shell将中止;一 但这种情况不应被视为语法错误。

    既然你用过 #!/bin/sh running in posix mode . 从 手册页:

    历史版本的sh的行为尽可能接近,而 也符合POSIX标准。