Thursday, 1 September 2016

About the Exit Code

All commands you execute in bash set an exit code.

Use of Exit Codes

Exit codes can be used to manage the flow of control within a bash script.

How to Work with Exit Codes

The exit code of the last command executed, is stored in the special variable “$?”.

Exit codes are in the range of 0 .. 255:
  • 0 indicates that the last command executed successfully.
  • All other values indicate some error condition.


Let’s run some code to see:
  • How Bash initializes the exit code
  • How every command sets the exit code
  • That it makes sense to store an exit code
When a bash script starts, the exit code stored in $? is initialized with 0, i.e "no error".
# show the initial state of $ß
RESULT=$?
echo '$? is initialized with: '$RESULT

Now let's run a command that will produce an error, store the exit code, run some other commands and monitor the exit code along the way:
$ # create an error and store the exit code it produced
$ mkdir /test
mkdir: cannot create directory ‘/test’: Permission denied
$ RESULT=$?
$ # what is the current exit code?
$ echo '  $? is: '$?
  $? is: 0
$ # repeat the error
$ mkdir /test
mkdir: cannot create directory ‘/test’: Permission denied
$ echo '  $? now is: '$?
  $? now is: 1
$ # what is it after the last echo command?
$ echo '  and now it is: '$?
  and now it is: 0
$ # here is the value we stored
$ echo "The exit code wie stored is: "$RESULT
The exit code wie stored is: 1

The interesting thing here is that assigning the exit code to the RESULT variable is a successful command and will reset the exit code to 0 again.
Even using the echo command (which will succeed most of the time) will reset the exit code.

The thing to keep in mind is to store an exit code if you cannot process it immediately, because everything you do after the error occurred will reset the exit code to some new value.

No comments:

Post a Comment