gpt4 book ai didi

bash - Bash脚本错误检查

转载 作者:行者123 更新时间:2023-12-03 08:00:01 25 4
gpt4 key购买 nike

我有点像Bash新手(就脚本而言),想知道错误检查的首选方法。我正在编写一个通过多个命令的构建脚本,并且我希望如果任何一个命令以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.

关于bash - Bash脚本错误检查,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25733242/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com