13 Oct 2007

Bash prompt with exit status

Let's improve the Bash prompt even further from my last post. I want to see the exit status of the last command in the bash prompt.

All (good written) programs have different exit status depending on how they where terminated. Exit status "0" is equivalent to "I terminated normally", all other exit status codes are the same as "non-normal exit" or "something went wrong". Unfortunate, there is not defined any standard exit status table that can say something about what went wrong given a numeric exit status. That is up to the programmer to decide.

  lars@titan:~$ test 1 -eq 1
  lars@titan:~$ echo $?
  0
  lars@titan:~$ test 1 -eq 2
  lars@titan:~$ echo $?
  1
  lars@titan:~$ notanycommand
  bash: notanycommand: command not found
  lars@titan:~$ echo $?
  127

I know that the exit status is stored in "$?". I use that to colorize my prompt red if the exit status is anything but "0" ("all ok"). In the bash man page, there is a special variable that is exactly what I'm looking for:

PROMPT_COMMAND
  If set, the value is executed as a command prior to issuing each
  primary prompt.

So we create a small function and add it to ~/.bashrc:

function exitstatus {

        EXITSTATUS="$?"
        BOLD="\[\033[1m\]"
        RED="\[\033[1;31m\]"
        OFF="\[\033[m\]"

        if [ "$EXITSTATUS" -eq "0" ]
        then
                PS1="${BOLD}\u@\h:\w\$${OFF} "
        else
                PS1="${BOLD}\u@\h:\w${OFF}${RED}\$${OFF} "
        fi

        PS2="${BOLD}>${OFF} "

}

PROMPT_COMMAND=exitstatus

Fire up a new shell, and every command that has an exit status different than "0" puts a red marker in your prompt:

1 comment:

Ky said...

Lars, you might appreciate this thread and perhaps my answer to it.

Thanks for sharing your approach.

http://unix.stackexchange.com/questions/8396/bash-display-exit-status-in-prompt/39767#39767