Tuesday, June 7, 2011

Quick shell hack

As documented here, I once wrote a piece of bashrc that would color your shell's hostname consistently colored across logins, but variable across different hosts, allowing you some ease of distinction in your present host at a glance.

The backstory of this particular hack is relatively simple - a friend of mine, during one of our conversations, had come up with the idea, and asked me to implement it, because he was too {busy,lazy}, as he wanted a way to distinguish which of his systems he was logged into easily. I thought about it for awhile, and came up with a number of stupid hacks, but eventually settled on the following:


namedec=$(uname -n | $MD5 | cut -c 1-32)

hex=$namedec
length=$(echo $hex | wc -c | tr -d " ")
power=1

while [ $length -gt 2 ]
do
  length=$(( $length - 1 ))
done

decimal=0
while [ "%$hex%" != "%%" ]
do
  digit=$(echo $hex | cut -b 1)

  value=$(( $digit ))

  decimal=$(( $decimal + value ))
  hex=$(echo $hex | sed 's/^.//')
done

#echo "Decimal value: $decimal"
namecol=$(($decimal % 17))
#echo $namecol
color=$(($namecol + 30))

# PS1="\[\033[01;31m\]\u\[\033[00m\]@\[\033[01;${color}m\]\h\[\033[00m\]:\[\033[01;34m\]\w\[\033[00m\] "
# green user vs red user for root
if [[ ${EUID} == 0 ]]
        then PS1="\[\033[01;31m\]\u\[\033[00m\]@\[\033[01;${color}m\]\h\[\033[00m\]:\[\033[01;34m\]\w\[\033[00m\] "
        PS1=${PS1}"# "
else
        PS1="\[\033[01;32m\]\u\[\033[00m\]@\[\033[01;${color}m\]\h\[\033[00m\]:\[\033[01;34m\]\w\[\033[00m\] "
        PS1=${PS1}"$ "
fi

# this actually works so um
#if [ $(which md5sum 2>&1 | grep "command not found" | wc -l) = "1" ]
#       then PS1='OMG THIS SYSTEM SUCKS \$ '
#elif [ $(which md5sum 2>&1 | grep "no md5sum in " | wc -l) = "1" ]
#       then PS1='OMG THIS SYSTEM SUCKS \$ '
#fi

You may note a few things here - one is the lack of syntax highlighting. As a result, have a screenshot for some clarity of the end result.



Another is that the source of the highlighting is rather silly and overkill. I played with a few variants on hashing the hostname until I settled on this, because a lot of the more "intelligent" ideas I came up with ended up with too many collisions, for reasons I was far too lazy to figure out for a Q&D hack like this.

It works, and it works well enough that my friend took it, threw it in his bashrc, and as far as I know, still keeps it there on his systems. I do as well, simply because it's convenient.

(Footnote - I have some terrible wrappers which try to set up the environment correctly to have a hash sourcing program based  on the uname -v output and checking  various paths, which I elided here because they're not part of the "interesting code", so to speak.)

No comments:

Post a Comment