Wednesday, March 12, 2008

Color-Coding My Prompt


Unless you're the 1-in-12 -- a colorblind white male -- color is a great cue.

I use stoplight colors to tell me when commands succeed and fail: red for failure, green for success. [Click on the image to enlarge it.]

It's less jarring than a flash or a beep.

It's also more persistent, like logging. If I get distracted, the next time I look at the screen, I still see the outcome; there doesn't even need to be an error message.

This is often a good companion to logging, since I can send all the error messages to a log and still know whether the job succeeds or fails, so long as I'm careful to set exit codes correctly in my scripts.

Here's code from my .bashrc that does the trick. $PROMPT_COMMAND is documented in the bash man page.

I also use the usual trick to put stuff in the window decoration, so I've thrown it in to make the whole code block easy to cut-and-paste.
# put the current directory into the X window decoration
xpwd()
echo -ne "\e]0;${USER}@${HOSTNAME}: ${PWD/$HOME/~}\007"
}

# set up a pair of prompts -- one for success, one for failure
prompt ()
{
# color names
_NONE="\[\e[0m\]"
_RED="\[\e[01;31m\]"
_GREEN="\[\e[01;32m\]"
_BLUE="\[\e[01;34m\]"

# color success and failure differently
# for the shell, success is 0, failure 1
_COLOR[0]=${_GREEN}
_COLOR[1]=${_RED}

# color constant pieces of the prompt
_MACH="${_BLUE}\u@\h${_NONE}"
_PCH="\$ "

# I use the directory name for my indicator
_DIR[0]="${_COLOR[0]}\W${_NONE}"
_DIR[1]="${_COLOR[1]}\W${_NONE}"

# the array of prompts
_PS[0]="$_MACH:${_DIR[0]}$_PCH "
_PS[1]="$_MACH:${_DIR[1]}$_PCH "
}

# choose the prompt based on the exit status of the last command
prompt_func()
{
if [ $? -eq 0 ]
then
PS1=${_PS[0]}
else
PS1=${_PS[1]}
fi
xpwd
}
PROMPT_COMMAND=prompt_func

prompt
true
Update:

Aw heck. I cleaned up this code to post it. Last night, I stuck it into my .bashrc, and immediately found a bug. I'll fix it tonight. Grumble.

Update 2:

Okay. Fixed now. Sorry about that.

Unfortunately, Blogger seems not to be very good about indenting code the way I want. I'll have to investigate that further.

No comments: