Monitor Linux Exit Codes on the Command Line

As you may already know, when programs end in Linux they return a value to the shell known as an exit or error code. It’s often a zero when everything is OK and a positive or negative number when something goes wrong (the actual definition is program-dependent). Normally, this value is used by scripts to know if a command failed so that it can act accordingly. However, as a power user, it’s good to know about this value as well.

The most common way to determine what exit code was returned by a command is to output the contents of the special shell variable ‘?’ to the console. This is accomplished as follows:

echo $?

For example,

~$ date
Wed Nov 13 21:24:07 PST 2007
~$ echo $?
0
~$ _

Here, I ran the date command which displayed the current system date/time. Then, by echoing the ‘?’ variable, I see that the date command exited with a code of zero indicating that everything was fine. Contrast this with the following:

~$ ls foo
ls: foo: No such file or directory
~$ echo $?
2
~$ _

According to the man page for the ls command, the exit codes are defined as “Exit status is 0 if OK, 1 if minor problems, 2 if serious trouble.” Since there was no file or directory named ‘foo’, the ls command returned an exit code of two to indicate “serious trouble”.

OK, so what if you always want to be able to tell what the exit code of a command is without having to always remember to echo it to the console? Well, you can add the value to the command prompt. Simply insert the string ‘$?’ wherever you like in your existing prompt string (PS1, PS2, PS3 and/or PS4).

My original PS1 was

‘u:w$ ‘

which looks like,

peter:~$ _

So, I added ‘:E$?’ between the user name (u) and colon and exported the new string to PS1.

export PS1=’u:E$?:w$ ‘

Now, my prompt looks like,

peter:E0:~$ _

I added the ‘E’ character to remind me that this is an error/exit code but you can leave it off. Going back to the ls example, let’s see what happens with the new prompt.

peter:E0:~$ ls foo
ls: foo: No such file or directory
peter:E2:~$ _

As you can see, my new prompt makes the exit code 2 plainly visible. I no longer have to bother to type the echo command and I can even check previous exit codes in the backscroll buffer. You can’t do that with the echo command since the ‘?’ shell variable is overwritten after every command.

Got more cool Linux tricks? Share them in the comments.

3 thoughts on “Monitor Linux Exit Codes on the Command Line”