Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to check the exit status using an if statement

What would be the best way to check the exit status in an if statement in order to echo a specific output?

I'm thinking of it being

if [ $? -eq 1 ] then    echo "blah blah blah" fi 

The issue I am also having is that the exit statement is before the if statement simply because it has to have that exit code. Also, I know I'm doing something wrong since the exit would obviously exit the program.

like image 537
deadcell4 Avatar asked Oct 31 '14 13:10

deadcell4


People also ask

What is the command to check exit status?

Checking Exit Status of Command command to get the status of executed command. for exmaple, if you have executed one command called “ df -h “, then you want to get the exit status of this command, just type the following command: $ echo $? From the above outputs, you can see that a number 0 is returned.

What is exit status command if it returns success?

Every command returns an exit status (sometimes referred to as a return status or exit code). A successful command returns a 0, while an unsuccessful one returns a non-zero value that usually can be interpreted as an error code.

Which command should I use to display the exit code of the previous command?

The echo command is used to display the exit code for the last executed Fault Management command.

What is the exit status of the command that was last run?

Every command that runs has an exit status. That check is looking at the exit status of the command that finished most recently before that line runs. If you want your script to exit when that test returns true (the previous command failed) then you put exit 1 (or whatever) inside that if block after the echo .


1 Answers

Every command that runs has an exit status.

That check is looking at the exit status of the command that finished most recently before that line runs.

If you want your script to exit when that test returns true (the previous command failed) then you put exit 1 (or whatever) inside that if block after the echo.

That being said, if you are running the command and are wanting to test its output, using the following is often more straightforward.

if some_command; then     echo command returned true else     echo command returned some error fi 

Or to turn that around use ! for negation

if ! some_command; then     echo command returned some error else     echo command returned true fi 

Note though that neither of those cares what the error code is. If you know you only care about a specific error code then you need to check $? manually.

like image 164
Etan Reisner Avatar answered Oct 11 '22 02:10

Etan Reisner