October 2, 2009

Red BASH Prompt on Error

This tweak will give you a minimal BASH prompt that prepends the exit code of the last command, in red, only in the event of an error.

Add this to the end of your ~/.bashrc file:
RED='\e[0;31m'
ESC='\e[0m'
PROMPT_COMMAND='RETURN=$?; echo -ne "\033]0;${USER}@${HOSTNAME%%.*}:${PWD/#$HOME/~}"; echo -ne "\007";'
EXIT_CODE='$(if [[ $RETURN = 0 ]]; then echo -ne ""; else echo -ne "\[$RED\]$RETURN\[$ESC\] "; fi;)'
PS1="$EXIT_CODE\u@\h:\W\$ "
And give it a try:
[me@myserver ~]$ source ~/.bashrc
me@myserver:~$ cat /non-existent-file
cat: /non-existent-file: No such file or directory
1 me@myserver:~$ ps
PID TTY TIME CMD
11032 pts/0 00:00:01 bash
12943 pts/0 00:00:00 ps
me@myserver:~$ false
1 me@myserver:~$ true
me@myserver:~$
More info on customizing your prompt over at IBM: Tip: Prompt magic

1 comments:

Adam Crews said...

I did something similar, but more extreme. Here's my posting about it.