Bash – Different color prompts for different machines when using terminal/ssh

bashcommand-line-interface

I have 5 machines I constantly ssh into to do work. Its getting increasingly frustrating when I am issuing wrong commands on wrong boxes. Luckily I havent done anything bad yet. I wanted to know if there is any hack which I can hardcode which will display my prompt in different colors based on the machine I am ssh into? Such as blue for desktop1, purple for laptop, red for server etc? Is this possible?

Currently I am using this command export PS1="\e[0;31m[\u@\h \W]\$ \e[m " taken from here http://www.cyberciti.biz/faq/bash-shell-change-the-color-of-my-shell-prompt-under-linux-or-unix/ but it obviously doesnt work across ssh.

Also, if you have any other cool bash tips for helping me ease my sight will be wonderful. I got this tip which colors the man pages.

http://linuxtidbits.wordpress.com/2009/03/23/less-colors-for-man-pages/

Best Answer

The method I use is to generate a color for the hostname from the hostname. There are not many colors to choose from so it will easily generate clashes, but it's useful for the small amount of machines that I manage.

hostnamecolor=$(hostname | od | tr ' ' '\n' | awk '{total = total + $1}END{print 30 + (total % 6)}')

PS1='\[\e]0;\w\a\]\n\[\e[32m\]\u@\[\e[${hostnamecolor}m\]\]\h \[\e[32m\]\w\[\e[0m\]\n$ '

The first line generates a number between 30 (inc) and 36 (exc) from the hostname of the machine. The second line applies it to the prompt with username and path in green (32) and the host name in the generated color.

No background colors are set, and I exclude cyan (36) and white (37) from the foreground to avoid clashes with the backgrounds of terminals that I use.