有效地检查几个命令的Bash的退出状态 [英] Checking Bash exit status of several commands efficiently

查看:111
本文介绍了有效地检查几个命令的Bash的退出状态的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有什么类似pipefail多个命令,就像一个'尝试'语句,但庆典之内。我愿做这样的事情:

Is there something similar to pipefail for multiple commands, like a 'try' statement but within bash. I would like to do something like this:

echo "trying stuff"
try {
    command1
    command2
    command3
}

和在任何时候,如果有命令失败,辍学和回声出命令的错误。我不希望有做这样的事情:

And at any point, if any command fails, drop out and echo out the error of that command. I don't want to have to do something like:

command1
if [ $? -ne 0 ]; then
    echo "command1 borked it"
fi

command2
if [ $? -ne 0 ]; then
    echo "command2 borked it"
fi

等等......之类的东西:

And so on... or anything like:

pipefail -o
command1 "arg1" "arg2" | command2 "arg1" "arg2" | command3

由于每个命令我相信(纠正我,如果我错了)的争论会互相干扰。这两种方法看似可怕的啰嗦和讨厌我,所以我在这里呼吁一个更有效的方法。

Because the arguments of each command I believe (correct me if I'm wrong) will interfere with each other. These two methods seem horribly long-winded and nasty to me so I'm here appealing for a more efficient method.

推荐答案

您可以编写一个启动和测试命令你的函数。假设命令1 命令2 是已设置命令环境变量。

You can write a function that launches and tests the command for you. Assume command1 and command2 are environment variables that have been set to a command.

function mytest {
    "$@"
    local status=$?
    if [ $status -ne 0 ]; then
        echo "error with $1" >&2
    fi
    return $status
}

mytest $command1
mytest $command2

这篇关于有效地检查几个命令的Bash的退出状态的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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