Automatically Show Exit Codes in Bash

March 15, 2019

When software stops running, it produces an exit code. In your shell (bash, zsh…), you can show the exit code using the $? variable:

terminal with exit code

# or, usually, as a one-liner...

$ echo something; echo $?

0 is good, any other value means something went wrong. Different values have different meanings, but it’s software specific.

That works … but it’s awkward. If you need the check the exit code, you need to remember running it immediately after the command you’re interested in. Otherwise, $? will be set to the exit code of whatever you ran after.

Showing $? Automatically

It doesn’t take too much Googling to find solutions to show the exit code after a command exits:

terminal with loud exit code

Here’s the code for your .bashrc:

# capture escape sequences for colors...
COLOR_RED=$(tput setaf 1)
ATTR_RESET=$(tput sgr0)

export PROMPT_COMMAND=show_exit_code
show_exit_code() {
  local exit=$?
  if [ "$exit" -ne 0 ]; then
    echo -e "${COLOR_RED}exit: ${exit}${ATTR_RESET}"
  fi
}

PROMPT_COMMAND:

Bash provides an environment variable called PROMPT_COMMAND. The contents of this variable are executed as a regular Bash command just before Bash displays a prompt.

What I like about this solution is that it doesn’t mess with PS1 (unlike other solutions) and it doesn’t show anything when the exit code is 0. I’ve never been a fan of complicated PS1 with a lot of fancy colors and statuses.

Discuss on Twitter