出错时自动退出 Bash shell 脚本 [英] Automatic exit from Bash shell script on error
问题描述
我一直在编写一些 shell 脚本,如果有任何命令失败时能够停止执行所述 shell 脚本,我会发现它很有用.请参阅下面的示例:
I've been writing some shell script and I would find it useful if there was the ability to halt the execution of said shell script if any of the commands failed. See below for an example:
#!/bin/bash
cd some_dir
./configure --some-flags
make
make install
所以在这种情况下,如果脚本无法切换到指定的目录,那么如果失败,它肯定不想在之后执行./configure.
So in this case, if the script can't change to the indicated directory, then it would certainly not want to do a ./configure afterwards if it fails.
现在我很清楚我可以对每个命令进行 if 检查(我认为这是一个无望的解决方案),但是是否有一个全局设置可以让脚本在其中一个命令失败时退出?
Now I'm well aware that I could have an if check for each command (which I think is a hopeless solution), but is there a global setting to make the script exit if one of the commands fails?
推荐答案
使用 set -e
内置:
Use the set -e
builtin:
#!/bin/bash
set -e
# Any subsequent(*) commands which fail will cause the shell script to exit immediately
或者,您可以在命令行上传递 -e
:
Alternatively, you can pass -e
on the command line:
bash -e my_script.sh
您也可以使用 set +e
禁用这种行为.
You can also disable this behavior with set +e
.
您可能还想使用全部或部分 -e
-u
-x
和 -o pipefail
选项如下:
You may also want to employ all or some of the the -e
-u
-x
and -o pipefail
options like so:
set -euxo pipefail
-e
出错退出,-u
未定义变量出错,-o (for option) pipefail
退出命令管道故障.此处记录了一些问题和解决方法.
-e
exits on error, -u
errors on undefined variables, and -o (for option) pipefail
exits on command pipe failures. Some gotchas and workarounds are documented well here.
(*) 注意:
如果失败的命令是紧跟在 while 或 until 关键字之后的命令列表,if 或 elif 保留字之后的测试部分,部分在 && 或 || 列表中执行的任何命令,除了命令在最后的 && 或 || 之后,管道中的任何命令,但最后一个,或者如果命令的返回值被反转!
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
)
这篇关于出错时自动退出 Bash shell 脚本的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!