当任何命令(包括非简单命令)失败时退出的 Bash 脚本
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/47792745/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Bash script to exit when any command (including non-simple commands) fail
提问by Alexander Collins
I have a script
我有一个脚本
#! /bin/sh
set -eux
command_a
command_b | command_c
while [ true ]; do
command_d
done
I'd like this to fail when any command fails. If command_a
fails, the script fails, but if command_b
or command_d
(not sure about command_c
) fail, the script carries on.
当任何命令失败时,我希望它失败。如果command_a
失败,脚本将失败,但如果command_b
或command_d
(不确定command_c
)失败,脚本将继续执行。
采纳答案by Ashutosh Bharti
This should not happen if you are using set -eux
, may be I can tell better if I knew the actual command.
One way to achieve exiting can be to use ||
如果您正在使用set -eux
,则不应发生这种情况,如果我知道实际命令,我可能会说得更好。实现退出的一种方法是使用||
while [ true ]; do
command_d || exit 1
done
a || b
means "do a (completely). If it didn't succeed, do b"
a || b
意思是“做a(完全)。如果没有成功,做b”
Also, you should use set -euxo pipefail
另外,你应该使用 set -euxo pipefail
Refer this: https://vaneyckt.io/posts/safer_bash_scripts_with_set_euxo_pipefail/
请参阅:https: //vaneyckt.io/posts/safer_bash_scripts_with_set_euxo_pipefail/