bash - 出错时自动退出 Bash shell 脚本

标签 bash shell error-handling exit

<分区>

我一直在编写一些 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)

关于bash - 出错时自动退出 Bash shell 脚本,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53677710/

相关文章:

bash - 替换多个模式,但不是用相同的字符串

php - 当存储过程插入语句具有重复的主键或不成功时,显示错误消息

php - 逻辑运算符: is AND better than OR?

linux - 使用 df -h 如何创建自定义警报条件

regex - Shell 脚本(用于移动文件的正则表达式)

.net - 从您的方法返回异常是不好的做法

linux - bash 管家脚本需要权限才能删除文件夹中的不同文件夹和文件

linux - 在 Bash 输出中获取特定文本

mysql - 将数百万行重新格式化为 CSV 的最快方法

linux - 为什么 Linux grep 没有给出正确的换行符计数?