Monday, March 24, 2008

How to check the exit status code

When a command finishes execution, it returns an exit code. The exit code is not displayed on the screen by default. To examine the exit code, you need to examine a special variable, "$?"

Say, you are searching for a string in a text file.

$ grep x1y2z3 somefile.txt

The standard output of the command returns null, which is a pretty good indication that the string cannot be found in the file.

But what if you embed the grep command in a script? How can you tell if the string is found or not?

Checking the exit code will tell you. Let's first try it out interactively.

$ grep x1y2z3 somefile.txt
$ echo $?

Note that in bash, the exit status is 0 if the command succeeded, and 1 if failed. For grep, 0 means that the string was found, and 1 (or higher), otherwise.

To check the exit status in a script, you may use the following pattern:

somecommand  argument1 argument2
[ $RETVAL -eq 0 ] && echo Success
[ $RETVAL -ne 0 ] && echo Failure


Mad MAx said...

is not correct.
when you assign a value to a variable, in bash, you can't prepend variable name with $.
The correct form is


regards, Mad Max.

Peter Leung said...

Thanks, Mad MAx.
I made the correction.

Anonymous said...

You can also just avoid the RETVAL altogether and use the "||" or "&&" operands which are called when the command on the left returns 1 or 0 respectively, e.g.

# grep returns 1, e.g. no match
grep foo /tmp/bar.txt || echo "text not found"

# grep returns 0, e.g. match
grep baz /tmp/bar.txt && echo "found it!"

Wang said...

Thanks for sharing, and thanks for the above comment.

Edward Kirton said...

it's unnecessary to use $? explicitly; the following is easier to read:


if ls *.sh
echo "ls Success"
echo "ls Failure">&2

if foo
echo "foo Success"
echo "foo Failure">&2