I want to have a standard BASH PS1 prompt that will automatically have a colour set based upon the hostname of the server.
This would meant that whenever logging into a server, it would instantly be clear and familiar that you are on that server as the prompt colour would be different to other servers
A given hostname must always give the same colour
I have found similar ideas with hex codes, but this is specifically for use with BASH colours
The idea would then be that there can be a standard bash prompt code snippet that can be included everywhere and will always give different colours for different servers without any further code changes
In a nutshell, the question is what bash function could you write that will take 2 arguments - a string and a hash. It should echo out the string in a colour that is determined by the hash, and the colour should always be the same for any given hash
EDIT - TO CLARIFY
the answers so far assume that host names are known in advance
I am looking for something that will assign the same random colour deterministically based on whatever host name is for that server
I am definitely not looking for something that requires any kind of code change when installing the PS1 on a new server
This post is along the lines but doesn't seem to have a simple PS1 snippet that I can use https://aweirdimagination.net/2015/02/28/better-hash-based-colors/
I am looking for something that will assign the same random colour deterministically based on whatever host name is for that server
Take a hashing algorithm and compute the hash of the hostname - as to convert a string to numbers. Then use this pseudorandom-number to generate a color.
gen_prompt_function() {
local number
number=$(
# get "random" string that depends on hostname
md5sum <<<"$HOSTNAME" |
# meh - take first byte and convert it to decimal
cut -c-2 | xargs -i printf "%d\n" "0x{}" |
# convert 0-255 range into 30-37 range
awk '{print int($0/255.0*(37-30)+30)}'
)
printf '\[\e[%d;1m\]%s\[\e[m\]' "$number" "$HOSTNAME"
}
PS1="$(gen_prompt_function)"'$ '
Read ANSI escpe sequences, tput and about color handling in terminfo and bash manual controlling prompt. Remember to add \[
\]
around color codes.
PS. In my bash adventures solely for hostname prompt coloring I have written a color handling script that generates a rainbow from 3 RGB colors taken from first 18 characters extracted from hash of a string, like in screeshot below. That script is used in my PS1 configuration.