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.
To check the exit code we can simply print the $? special variable in bash. This variable will print the exit code of the last run command.
To display the exit code for the last command you ran on the command line, use the following command: $ echo $? The displayed response contains no pomp or circumstance. It's simply a number.
“$?” is a variable that holds the return value of the last executed command. “echo $?” displays 0 if the last command has been successfully executed and displays a non-zero value if some error has occurred. The bash sets “$?” To the exit status of the last executed process.
For the bash shell's purposes, a command which exits with a zero (0) exit status has succeeded. A non-zero (1-255) exit status indicates failure. If a command is not found, the child process created to execute it returns a status of 127.
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 != 0 )); then echo "error with $1" >&2 fi return $status } mytest "$command1" mytest "$command2"
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With