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 $?
1

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=$?
[ $RETVAL -eq 0 ] && echo Success
[ $RETVAL -ne 0 ] && echo Failure

5 comments:

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

    RETVAL=$?

    regards, Mad Max.

    ReplyDelete
  2. Thanks, Mad MAx.
    I made the correction.
    Peter

    ReplyDelete
  3. 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!"

    ReplyDelete
  4. Thanks for sharing, and thanks for the above comment.

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

    #!/bin/bash

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

    if foo
    then
    echo "foo Success"
    else
    echo "foo Failure">&2
    fi

    ReplyDelete