Command Return Codes and Long Command Prompts

Once you’ve been using a tool for a while you often reach a plateau where it’s “good enough” and you stop looking for ways to tweak it. I’ve been using bash for a number of years and I’ve got set in my ways; until I sat next to a co-worker who uses zsh.

My first Linux machine had a 14” monitor that could only do low resolutions. Screen space was at a premium and every character was precious. These days most of the machines I spend a lot of time on have 19-21 inch monitors. Unfortunately, I still have the same bash prompt.

As screen estate isn’t quite so precious anymore I’ve changed to a two line prompt:
$ type_commands_here

This gives me all the details of where I am (with each part allowing double click selection, ready for pasting in another terminal) while also having an almost empty line ready for my commands. While it still feels a little strange, after eight years of using a single line prompt, it’s growing on me.

The other little bash tweak I’ve added recently, and this was inspired by zsh, is to show all non-zero return codes from commands I’ve run in the shell. As most of you know, a majority of unix command line tools return ‘0’ on success. If it returns a different exit code then something is probably wrong. While you can check the exit code explicitly with an ‘echo $?’ this soon becomes very, very tedious. After mentioning what I wanted to do, a number of sample command lines and scripts bounced around the GLLUG list. After some discussion Tethys came up with this little bit of magic:

show_exit_code() {
  if [ $retval -ne 0 -a "$HISTCMD" != "$lastcmdnum" ];then
    echo " -- exit code: $retval"

export PROMPT_COMMAND=show_exit_code

If you add this to your .bash_profile (or .bashrc if you source that) every time a command returns a non-zero code the shell will show it to you. This snippet also handles a number of the edge cases, it doesn’t get in the way of piping, if a command returns a bad value and you press enter or Ctrl-C the code isn’t displayed again and some other annoying bits my initial version didn’t deal with.