Bash Shell $PS1 Configuration

After a recent talk with Jim Meyering I’ve decided to finally organise a bit my .bashrc and all my .dot_files in general.

So first and foremost important change, track all .dot_files in some for of version control system. I’m right now using Mercurial powered by BitBucket. Git is also a great choice. Go with whatever you are comfortable with, just make sure you don’t lose your precious configs and that you can easily synchronise all you unix/linux/bsd boxes effortlessly.

The other big take for this talk was to make sure your $PS1 shell prompt gives you the right information. Two key things that are absolute gold to have:

  1. The branch/bookmark you are currently in if you are in a VCS directory.
  2. The exit code of the previous command if it returned an error (different from 0).

Here’s how my current $PS1 looks like:

.bashrc $PS1

And this is my current .bashrc $PS1 configuration:

############################################
# Decorate $PS1
############################################
function __get_vcs {
local path=`pwd`
while true; do
if [[ -d "${path}/.hg" ]]; then
echo "mercurial"
return
elif [[ -d "${path}/.git" ]]; then
echo "git"
return
elif [[ "${path}" = "/" ]]; then
echo "none"
return
fi
path=`cd ${path}/../ && pwd`
done
}

function __get_vcs_branch {
vcs="$(__get_vcs)"
out=''
case "$vcs" in
"mercurial")
out=`hg id -b`
out=" (hg:${out})"
;;
"git")
out=`git rev-parse --abbrev-ref HEAD`
out=" (git:${out})"
;;
*)
out=''
;;
esac
echo "$out"
}

function __get_exit_code {
local code="$?"
local msg=''
if [ $code != 0 ]; then
msg="[${code}] "
fi
echo "$msg"
}

red='\[\033[01;31m\]'
green='\[\033[00;32m\]'
purple='\[\033[01;35m\]'
yellow='\[\033[01;33m\]'
blue='\[\033[01;34m\]'
black='\[\033[00m\]'
export PS1="${red}\$(__get_exit_code)${blue}\t ${green}\W${purple}\$(__get_vcs_branch)${blue} \$${black} "

Finally, here are some other things that could be interesting to display:

  • \u – Username
  • \h – Hostname
  • \w – Full path of the current working directory

PS: Word of advice, it’s very easy to get carried away and try to add ‘the world information’ to your $PS1. Up to you what you value the most.