Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Checking Bash exit status of several commands efficiently

Tags:

bash

exit

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.

like image 534
jwbensley Avatar asked Mar 04 '11 15:03

jwbensley


People also ask

How do you check exit status in bash?

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.

How do you get the exit status of the most recently run command in bash?

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.

What is exit status How do you check the exit status?

“$?” 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.

Which of the following correctly identify the exit status when a bash shell script finishes successfully?

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.


1 Answers

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" 
like image 180
krtek Avatar answered Sep 17 '22 13:09

krtek