Scripting – Generate a Color Code from an Arbitrary String

colorspromptscriptingzsh

I want my shell prompt to have a different, unique, consistent color automatically based on the hostname of the server.

For example, when I log in to a particular server, the prompt should be a color specific to that server, which will be the same the next time I log in to that server. I don't want to hard code any mapping of server names to colors. It doesn't have to be a beautiful color, but it would be good if it had high contrast with a dark background.

So, perhaps I could create a deterministic hash of the hostname and convert that into a color code usable by the prompt.

How would I do that?

Best Answer

I ended up doing this

# get hash and byte size
prompt_hash_and_size=`hostname|cksum`
# get hash part and apply modulo 256 to put it in range 1..255
prompt_hashcolor=$(echo $prompt_hash_and_size|awk '{print $1%255 + 1}')
# use it as background color in prompt
PROMPT="%K{${prompt_hashcolor}}%F%~%f%k%  "

you can compact it to

prompt_hashcolor=$(hostname|cksum|awk '{print $1%256}')
Related Question