I SSH in to many different computers all day, and sometimes I get confused by what machine I’m on. I was thinking about assigning a different color in my bash prompt for each machine, but I thought that would get tiresome coming up with a new color for each new box that I had to log in to. I mentioned this in the Chicago Tech Slack and Josh Symonds suggested “Some prompts do some hashing on hostnames to turn the prompt a different color based on that.”

So that’s what I did. My bash prompt already has the hostname in the prompt, so I updated it to give it a different color for each hostname, based on hashing the hostname. It looks like this.

Different colored hostnames in the bash prompt

Now, each of the three hosts parker, clifford and alex have a different color, which can help give a visual cue if something’s wrong.

I’m a big believer in using color to help in orienting. The best demonstration I had was when I accidentally walked into the women’s bathroom at work. I just stood there in the doorway thinking “Wait, what’s wrong?” I couldn’t identify it for a few seconds, but I knew something was wrong. Then it clicked: The wallpaper was a different color than I was used to.

Here’s how I did the magic with the prompt.

local EXIT="$?"  # Stash the exit status for later.

# List of color variables that bash can use
local BLACK="\[\033[0;30m\]"   # Black
local DGREY="\[\033[1;30m\]"   # Dark Gray
local RED="\[\033[0;31m\]"     # Red
local LRED="\[\033[1;31m\]"    # Light Red
local GREEN="\[\033[0;32m\]"   # Green
local LGREEN="\[\033[1;32m\]"  # Light Green
local YELLOW="\[\033[0;33m\]"  # Yellow
local LYELLOW="\[\033[1;33m\]" # Light Yellow
local BLUE="\[\033[0;34m\]"    # Blue
local LBLUE="\[\033[1;34m\]"   # Light Blue
local PURPLE="\[\033[0;35m\]"  # Purple
local LPURPLE="\[\033[1;35m\]" # Light Purple
local CYAN="\[\033[0;36m\]"    # Cyan
local LCYAN="\[\033[1;36m\]"   # Light Cyan
local LGREY="\[\033[0;37m\]"   # Light Gray
local WHITE="\[\033[1;37m\]"   # White

local RESET="\[\033[0m\]"      # Color reset
local BOLD="\[\033[;1m\]"      # Bold

# Base prompt
local CNAME=$(hostname -s)

local CNAME_MD5
if [ "${OSTYPE:0:6}" == 'darwin' ] ; then
    CNAME_MD5=$(hostname -s | md5)
    CNAME_MD5=$(hostname -s | md5sum)

local RDEC=$((16#${CNAME_MD5:0:2}))
local GDEC=$((16#${CNAME_MD5:2:2}))
local BDEC=$((16#${CNAME_MD5:4:2}))
PS1="\[\e[38;2;${RDEC};${GDEC};${BDEC}m\]$CNAME:$YELLOW\w$CYAN "
if [ "$EXIT" != 0 ]; then
    PS1+="${LRED}\\\$ $RESET"
    PS1+="${LGREEN}\\\$ $RESET"

There’s other stuff in my prompt setup to show the status of the Subversion or Git project I’m working on, too.

I hope someone finds this useful. Drop me an email at andy@petdance.com with any suggestions on improvements.