当任何命令(包括非简单命令)失败时,退出Bash脚本 [英] Bash script to exit when any command (including non-simple commands) fail

查看:59
本文介绍了当任何命令(包括非简单命令)失败时,退出Bash脚本的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个脚本

#! /bin/sh
set -eux

command_a

command_b | command_c

while [ true ]; do
    command_d
done

当任何命令失败时,我希望此操作失败.如果 command_a 失败,则脚本会失败,但是如果 command_b command_d (不确定 command_c )失败,则脚本会失败.脚本继续进行.

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.

推荐答案

如果您使用的是 set -eux ,则不应发生这种情况,如果我知道实际的命令,也许可以告诉我更多.实现退出的一种方法是使用 ||

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 ||

while [ true ]; do
    command_d || exit 1
done

a ||b 的意思是(完全)执行a.如果未成功,则执行b".

a || b means "do a (completely). If it didn't succeed, do b"

此外,您应该使用 set -euxo pipefail

请参阅以下内容: https://vaneyckt.io/posts/safer_bash_scripts_with_set_euxo_pipefail/

这篇关于当任何命令(包括非简单命令)失败时,退出Bash脚本的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆