我有点像Bash新手(就脚本而言)并想知道错误检查的首选方法。我正在编写一个构建脚本,它经历了许多命令,如果任何命令以0以外的任何其他命令退出,我希望脚本停止。除了在每个命令之后检查响应代码之外,是否存在“通用”方式如果任何东西返回非0,退出脚本?谢谢!
答案 0 :(得分:0)
在脚本开头使用set -e
。
在命令失败后,它将停止脚本运行,并且将转发错误代码。
来自bash文档:
-e Exit immediately if a pipeline (which may consist of a single simple command), a subshell command enclosed in parentheses, or one of the commands executed as part of a command list enclosed by braces (see SHELL GRAMMAR above) exits with a non-zero status. 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 !. A trap on ERR, if set, is executed before the shell exits. This option applies to the shell environment and each subshell envi- ronment separately (see COMMAND EXECUTION ENVIRONMENT above), and may cause subshells to exit before executing all the commands in the subshell.