How to configure bash to print exit status for every command?

The exit code from the last executed command is stored in the $? environment variable. So you just can add this variable to the default command prompt and you will always have the exit code printed there. The prompt is stored in the $PS1 environment variable. It is initially set in the /etc/bash.bashrc script and later in the $HOME/.bashrc.

So edit the line in $HOME/.bashrc (/etc/bash.bashrc would be system wide) from it's default value:

PS1='${debian_chroot:+($debian_chroot)}\u@\h:\w\$ '

to this (for example):

PS1='${debian_chroot:+($debian_chroot)}\u@\h:\w[$?] \$ '

So the default prompt in changed to:

user@host:/path/to/dir[0] $

The 0 in the brackets is your exit code, see:

user@host:~[0] $ ls
user@host:~[0] $ ls /root/
ls: cannot open directory /root/: Permission denied
user@host:~[2] $ ^C
user@host:~[130] $

For the meanings see http://www.tldp.org/LDP/abs/html/exitcodes.html


Another way that I picked from the Arch Wiki was to use trap:

EC() { echo -e '\e[1;33m'code $?'\e[m\n'; }
trap EC ERR

Effect:

$ ( exit 1 )
code 1

$ some-non-existent-command
some-non-existent-command: command not found
code 127

$

Here is a simple example:

PS1='$? > '

If using double quotes, then you have to add a backslash to escape the $:

PS1="\$? > "

Output:

0 > echo 'ok'
ok
0 > bogus
bogus: command not found
127 > 

An even better way is to only print the exit code when it is non-zero.

PS1='${?#0}> '    # single quote example
PS1="\${?#0}> "   # double quote example (requires extra backslash)

Sample output:

> echo 'ok'
ok
> bogus
bogus: command not found
127> 

Explanation: ${var#pattern} is a bash parameter expansion that means remove the shortest matching pattern from the front of $var. So in this case, we are removing 0 from the front of $?, which would effectively truncate an exit code of 0.

If using double quotes, $? would be substituted when PS1 is set, instead of being evaluated each time. Do echo $PS1 to confirm you don't have a hardcoded value in PS1.

Tags:

Bash