hashtext-coloring

How to color code a hostname from bash or python?


I am looking for a simple solution that would give me a RGB color for each hostname.

I plan to use this for setting the tab-color in iTerm2, so I can easily spot the correct host based on the the color picket for it.

Now, I cannot use all 3-bytes because in some cases the differences can be too subtile, and also because I need to ban too dark to too light color.

Bases on this I can only assume that I could safely use 5 bits for each color, this would give me something like 2^15 = 128 colors to pick from. I can take care of the formula for converting the number to R,G,B values ;)

So what I need is a simple piece of code that would give me a 15 bit hash of a string (hostname).

If this would be doable in bash, it would be perfect, but I also accept a Python variant. 

The solution has to work on Debian, RedHat and OS X without having to install additional utils or libraries.


Solution

  • #!/bin/bash
    MD5="md5sum"
    if [[ $OS == 'darwin' ]]; then MD5="md5" ; fi
    HASH=`hostname -s | ${MD5}`
    echo -n -e     "\033]6;1;bg;red;brightness;$((0x${HASH:0:2}))\a\033]6;1;bg;green;brightness;$((0x${HASH:2:2}))\a\033]6;1;bg;blue;brightness;$((0x${HASH:4:2}))\a"