SOHO : Small Office Home Office
Freeware - Opensource software tips, tricks, tweaks & fixes for managing, securing, improving the performance of SOHO Desktop, Laptop, Networks

Thursday, April 5, 2012

Adding color to bash shell prompt

Mistakes do happen if not taken care off.

Other day I was handling two servers at the sametime. It so happend that the commands to be executed on  server-1 ended on server-2, this was a disaster. To avoid this I have set colored prompts to easily identify the servers. While I was doing this, I also modified the profiles to change colors for local user and root user. Now its easy to identify as to which server I am on and as a local or a root user. 

We are using ubuntu servers and to set the colored prompts I modified the .bashrc file. The .bashrc file is located in the users home directory. We have set green colored prompt for server-1 and blue colored prompt for server-2.

To set green color prompt for local user on server-1 append the following line to users .bashrc file.
export PS1="\e[0;32m[\u@\h \W]\$ \e[m"
To identify the root account we have hightlight the background with the same green color and red colored text. Append the following line to the root .bashrc 
export PS1="\e[0;31m\e[42m\u@\h \w> \e[m"

The image below will help you understand better.
click on image to enlarge

The code and its function


Change background color of the prompt
Change the background color by specifying \e[{code}m in the PS1 prompt as shown below.
Example:
$ export PS1="\e[47m\u@\h \w> \e[m"
[Note: This is for Light Gray background]
Combination of background and foreground
export PS1="\e[0;34m\e[47m\u@\h \w> \e[m"
[Note: This is for Light Blue foreground and Light Gray background]
Add the following to the .bash_profile or .bashrc to make the above background and foreground color permanent.
STARTFGCOLOR='\e[0;34m';
STARTBGCOLOR="\e[47m"
ENDCOLOR="\e[0m"
export PS1="$STARTFGCOLOR$STARTBGCOLOR\u@\h \w> $ENDCOLOR"
Play around by using the following background color and choose the one that suites your taste:
  • \e[40m
  • \e[41m
  • \e[42m
  • \e[43m
  • \e[44m
  • \e[45m
  • \e[46m
  • \e[47m

Foreground Color Code Table:

Black 0;30
Blue 0;34
Green 0;32
Cyan 0;36
Red 0;31
Purple 0;35
Brown 0;33
[Note: Replace 0 with 1 for dark color]

No comments:

Post a Comment