Set tmux status line color based on hostname

I came up with the following shell function:

hash_string256() {
    # Hash $1 into a number
    hash_value=$(printf "%s" "$1" | md5sum |tr -d " -"| tr "a-f" "A-F")
    # Add the hash with $2 and modulo 256 the result
    # if $2 == "" it is 0
    printf "ibase=16; (%s + %X) %% 100\n" $hash_value "$2" | bc
}

This function can be used like this (The results are true if $HOST is LOL):

$hash_string256 $HOST
 113
$hash_string256 $HOST 127
 240

To connected it with tmux you can use a script that starts and configures tmux.

#!/bin/sh
SESSION=$USER

hash_string256() {
    hash_value=$(printf "%s" "$1" | md5sum |tr -d " -"| tr "a-f" "A-F")
    printf "ibase=16; (%s + %X) %% 100 \n" $hash_value "$2" | bc
}

tmux -2 new-session -d -s $SESSION

tmux set -g status-fg colour$(hash_string256 $HOST)
tmux set -g status-bg colour$(hash_string256 $HOST 127)

# Attach to session
tmux -2 attach-session -t $SESSION

For the hostname LOL it would set the status-fg to colour113 and status-bg to colour240. The number 127 in $(hash_string256 $HOST 127) is there so the background will be not the same as the foreground color and far apart from each other.

For none GNU systems

If your system has md5 instead of md5sum the line

hash_value=$(printf "%s" "$1" | md5sum |tr -d " -"| tr "a-f" "A-F")

can be replaced with

hash_value=$(printf "%s" "$1" | md5 | tr "a-f" "A-F")

I wanted this feature as well. I basically merged everything into this .tmux.conf

# cat <<__DATA__ >/dev/null
# Embed shell scripts

set -g status-utf8 on
set -g utf8 on

set -g default-terminal "screen-256color"

run "cut -c3- ~/.tmux.conf | bash -s apply_configuration"

# __DATA__
#
# apply_configuration() {
#    tmux set -g status-bg colour$(hash_string256 $(hostname))
# }
# hash_string256() {
#      hash_value=$(printf "%s" "$1" | md5sum | sed -e 's/[^[:alnum:]]\+//g' | tr "a-f" "A-F")
#      if [ "x" != "x$2" ]
#      then
#          v2="+ $2"
#      fi
#      echo "$(((0x$hash_value $v2) % 255))" | tr -d "-"
# }
# 
# $1

I removed using bc because I didn't have it in my git-bash. Thus I wanted it to work on both my linux systems and windows with cygwin without adding extra stuff.

Tags:

Colors

Tmux