November 20, 2011

Unix Prompt

Arriving at my new working place, I wanted to install my own .bashrc and other dotfiles, like I had on my previous work station.

But this time, I wanted a distinguishable prompt with nice colors and still easy for the eyes. So I decided to go on with the Solarized theme and installed it for PuTTY, Vim and other tools I use on a daily basis.

The next little challenge for me was to clearly differenciate the command line in my prompt (the things I type) with another color than the output that gets generated. After a few research on the net, I’ve found a solution that works pretty well.

I’m using bash, and here is a screen of PuTTY on my Windows 7 work station:

The solution was to use thre trap command to reset the colors before the shell outputs something, and let the color in white at the end of PS1.

Here is an excerpt of my .bashrc

# Reset
Color_Off='\[\e[0m\]'       # Text Reset

# Colors will work nice when used with "Solarized" palette.
# Nothing new here
White='\[\e[0;37m\]'        # White
BPurple='\[\e[1;35m\]'      # Purple
Green='\[\e[0;32m\]'        # Green
Blue='\[\e[0;34m\]'         # Blue
Yellow='\[\e[0;33m\]'       # Yellow
Purple='\[\e[0;35m\]'       # Purple
BWhite='\[\e[1;37m\]'       # White

# custom prompt.
# User input is colored in white
# the trap will reset the colors before execution of commands
PS1="${BPurple}\A ${Green}\u${Color_Off}@${Blue}\h${Color_Off}:[${Yellow}\w${Color_Off}]${Purple}\n$ ${BWhite}"

# reset color after prompt
trap "echo -ne '\e[0m'" DEBUG

The trap command will execute echo -ne '\e[Om' before anything gets written on stdout, and thus will reset the color that was previously left to white. This is the only real trick in this post. Nevertheless, it’s still pretty cool.

Enjoy your nice prompt :)

Alexandre Grison - // - @algrison