我一直在编写一些 shell 脚本,如果有任何命令失败时能够停止执行所述 shell 脚本,我会发现它很有用。请参见下面的示例:
#!/bin/bash
cd some_dir
./configure --some-flags
make
make install
所以在这种情况下,如果脚本无法更改到指定的目录,那么它肯定不想在失败后执行 ./configure。
现在我很清楚我可以对每个命令进行 if 检查(我认为这是一个无望的解决方案),但是是否有一个全局设置可以在其中一个命令失败时退出脚本?
使用 set -e
内置:
#!/bin/bash
set -e
# Any subsequent(*) commands which fail will cause the shell script to exit immediately
或者,您可以在命令行中传递 -e
:
bash -e my_script.sh
您还可以使用set +e
禁用此行为。
您可能还想使用全部或部分 -e
-u
-x
和 -o pipefail
像这样的选项:
set -euxo pipefail
-e
出错退出,-u
undefined variable 出错,-x
在执行前打印命令,-o (可选)pipefail
在命令管道失败时退出。一些陷阱和变通方法已被很好地记录下来 here .
(*) 注意:
The shell does not exit if the command that fails is part of the
command list immediately following a while or until keyword,
part of the test following the if or elif reserved words, part
of any command executed in a && or || list except the command
following the final && or ||, any command in a pipeline but
the last, or if the command's return value is being inverted with
!
(来自 man bash
)