当任何命令(包括非简单命令)失败时退出的 Bash 脚本

Ale*_*ins 6 bash

我有一个脚本

#! /bin/sh
set -eux

command_a

command_b | command_c

while [ true ]; do
    command_d
done
Run Code Online (Sandbox Code Playgroud)

当任何命令失败时,我希望这失败。如果command_a失败,脚本将失败,但如果command_bcommand_d(不确定command_c)失败,脚本将继续执行。

小智 5

如果您正在使用set -eux,则不应发生这种情况,如果我知道实际命令,我可能会说得更好。实现退出的一种方法是使用||

while [ true ]; do
    command_d || exit 1
done
Run Code Online (Sandbox Code Playgroud)

a || b 意思是“做a(完全)。如果没有成功,做b”

另外,你应该使用 set -euxo pipefail

请参阅:https : //vaneyckt.io/posts/safer_bash_scripts_with_set_euxo_pipefail/