问题描述
我有一个Bash shell脚本,可以调用许多命令.
I have a Bash shell script that invokes a number of commands.
如果任何命令返回的非零值,我都希望shell脚本自动以返回值1退出.
I would like to have the shell script automatically exit with a return value of 1 if any of the commands return a non-zero value.
是否可以不显式检查每个命令的结果?
Is this possible without explicitly checking the result of each command?
例如,
dosomething1
if [[ $? -ne 0 ]]; then
exit 1
fi
dosomething2
if [[ $? -ne 0 ]]; then
exit 1
fi
推荐答案
将其添加到脚本的开头:
Add this to the beginning of the script:
set -e
如果简单命令以非零退出值退出,这将导致shell立即退出.简单命令是不属于if,while,或直到测试的一部分的任何命令,也不属于&&的一部分的任何命令.或||列表.
This will cause the shell to exit immediately if a simple command exits with a nonzero exit value. A simple command is any command not part of an if, while, or until test, or part of an && or || list.
有关"set"内部命令的更多信息,请参见 bash(1)手册页
See the bash(1) man page on the "set" internal command for more details.
我个人几乎所有的shell脚本都以"set -e"开头.当某个脚本在中间出现故障并顽固地破坏了其余脚本的假设时,固执地继续执行脚本确实很烦人.
I personally start almost all shell scripts with "set -e". It's really annoying to have a script stubbornly continue when something fails in the middle and breaks assumptions for the rest of the script.
这篇关于如果有任何命令返回非零值,则中止shell脚本的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!