Tips from RHCEs

Featured Article: Getting a colored shell prompt

by Richard Keech

Working in the world of the Linux command line is normally a monochromatic experience. However, the output of some commands, like ls, can utilise color-coded output to convey information in a more powerful way. Carefully chosen colors in interfaces can enhance their useability. Let's apply this thinking to the command prompt.

The main terminal emulator programs in Red Hat (gnome-terminal, konsole, xterm) can interpret standard escape sequences for cursor control and character effects. This includes the setting of colors. These escape sequences are standardised in ISO/IEC 6429:1992 "Information technology -- Control functions for coded character sets". On Red Hat Linux a reference to these can be found in the dir_colors(5) man page. So setting a colored prompt involves embedding ISO 6429 escape sequences in the Bash prompt string variable ($PS).

Aside from visual interest, why bother? Well, first it aids readability since the coloured prompts delimit the command-display-command-display in a terminal window. Second, it can aid security by making root shells more obvious. I use red to indicate a root shell. This makes it less likely that you will inadvertantly enter an inappropriate command in a root shell.

To illustrate the usefullness, shown here are two terminal windows, identical except for the colored prompts. Side-by-side comparison shows how the colored prompts aid readability, and emphasise the part where the shell has root privilege.

black prompt   colored prompt

To achieve this, get the file colorprompt.sh from http://people.redhat.com/rkeech/#color and put it in /etc/profile.d/ where it should be executable.

The colorprompt.sh file (simplified) looks like this:

lc='\[\e[1;' # lead-in character
RED=${lc}31m;
PURPLE=${lc}35m
RC=${lc}0m # reset character

if [ "$USER" = "root" ]
then
pc=$RED
else
pc=$PURPLE
fi

PS1="${pc}\]\u@\h \W\\$ ${RC}\]"

Notes; this method is written with Bash in mind. It is expected to work for other shells in an equivalent manner. Its use with the screen command has not been tested.