Search code examples
bashterminalxtermps1terminal-emulator

Maintainable approach for generating a machine-specific PS1 Prompt


To help myself remember that I am logged into a different system, quickly and visually, I use different colors for the \h field in the Bash PS1 environment variable.

I am looking for a way to reliably generate the PS1, tied to a static host-identifier; say, via the hostid command.

Originally, my PS1, which was adapted from something generated by bashrcgenerator.com, looked like:

export PS1="\u@\[$(tput bold)\]\[$(tput sgr0)\]\[\033[38;5;35m\]\h\[$(tput sgr0)\]\[$(tput sgr0)\]\[\033[38;5;15m\]\[$(tput sgr0)\]:\[\033[38;5;245m\]\w\[$(tput sgr0)\]\[\033[38;5;15m\]\[$(tput sgr0)\]\\$ "

What a mess.

So to start any progress, the first step was to do some refactoring. This landed me at the following script:

bold="$(tput bold)"
reset="$(tput sgr0)"
green="\e[38;5;35m"
gray="\e[38;5;245m"

directory='\w'
host='\h'
user='\u'

function colorize() {
    echo -n "${2}${1}${reset}"
}

export PS1="${user}@$(colorize $host $green):$(colorize $directory $gray)\\$ "

At this point, you can at least see what the heck is going on.

Now, I need to write a function like:

get_repeatable_color_for_hostid() {
    # hash the $(hostid) into a valid color escape string
    # e.g. 16ab1d60 --> \e[38;5;35m
}

In order to do so, I need to understand:

  • What are the meanings of the field portions xx;y;zzm inside of e.g. \e[38;5;35m?
  • How do I do the hashing from the hostid to that color escape sequence, s.t. colors are randomized as much as possible.

Solution

  • Regarding colors this page helped me a lot to understand all details: http://misc.flogisoft.com/bash/tip_colors_and_formatting

    Since there aren't so many colors to chose from one idea would be to simply assign a color to each of the host, and in case you have more hosts then group the hosts based on importance (dev, prod etc.) each group with it's own color.

    There is also this idea to generate the color (from 1 to 256) using the checksum of the hostname: COLOR=$(($(hostname | cksum | cut -f1 -d" ")%256+1))