Make bash show the return code

When using a command line interface, I like to see all the output a program makes. The standard out and error are already dumped to my console, but there is one piece of information usually hidden from the user: the return code.

Add the following to your .bashrc to get a nice notification if a program returns a non-zero code:

export PROMPT_COMMAND='ret=$?; if [ $ret -ne 0 ] ; then echo -e "returned \033[01;31m$ret\033[00;00m"; fi'

It looks like this:

user@host$ false
returned 1
user@host$

Posted

in

by

Tags:

Comments

6 responses to “Make bash show the return code”

  1. Damien Clauzel Avatar

    Excellent! Thanks a lot.
    Looking for return codes is always a pain.

  2. Ace McDoodson Avatar
    Ace McDoodson

    Why not just do echo $?

    1. david Avatar
      david

      This alerts me to the fact a command exit non-zero, rather than requiring me to go and check. I’m that lazy 😉

  3. bob Avatar
    bob

    with zsh I just do %F{red}%(?..!%?!) which gives me
    [… ]%false
    [… !1!]%true
    [… ]%

  4. Fadi (itoctopus) Avatar

    Hi David,

    Can you please dissect that line and explain it a bit? It would be really interesting to know how it works…

    What’s with the hex codes?

    1. david Avatar
      david

      Sure. First let’s reformat it:

      ret=$?
      if [ $ret -ne 0 ] then
          echo -e "returned \033[01;31m$ret\033[00;00m"
      fi
      

      The first thing we do is save the return code from $? into $ret, because subsequent commands, including [, will overwrite it. We then check if the return code is not equal to zero, i.e. is an error, and if so we print that string.

      There isn’t actually any hex codes – the “\033” is octal 33, which is the escape character in ASCII. This tells the terminal to start interpreting the next characters as ANSI escape codes. These can be quite complex, but you can generate them easily with the tput utility.

Leave a Reply to Ace McDoodson Cancel reply

Your email address will not be published. Required fields are marked *