Checking Bash exit status of several commands efficiently

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.

15 Answers
15

Leave a Comment