Tumbled Logic

Jul 30 2009

My bash prompt

My bash prompt has evolved somewhat over the years. Nowadays, it’s quite straightforward. As somebody who logs into a multitude of hosts and a variety of different users, it’s important for me to be able to see at a glance who the system thinks I am, what host I’m connected to, and whereabouts in the filesystem I happen to be. I recently extended it, thanks to this tip, to include the name of the git branch I’m working on, if appropriate.

This is what the relevant bits of my profile look like:

ansi_black='\[\e[30m\]'
ansi_red='\[\e[31m\]'
ansi_green='\[\e[32m\]'
ansi_yellow='\[\e[33m\]'
ansi_blue='\[\e[34m\]'
ansi_magenta='\[\e[35m\]'
ansi_cyan='\[\e[36m\]'
ansi_white='\[\e[37m\]'
ansi_bblack='\[\e[90m\]'
ansi_bred='\[\e[91m\]'
ansi_bgreen='\[\e[92m\]'
ansi_byellow='\[\e[93m\]'
ansi_bblue='\[\e[94m\]'
ansi_bmagenta='\[\e[95m\]'
ansi_bcyan='\[\e[96m\]'
ansi_bwhite='\[\e[97m\]'
ansi_normal='\[\e[0m\]'

PS1="${ansi_bwhite}[${ansi_bgreen}\\u${ansi_green}@${ansi_bgreen}\\h ${ansi_bmagenta}\$(gitbranch)${ansi_bcyan}\\W${ansi_bwhite}]\\\$${ansi_normal} "

gitbranch()
{
    branch=`( git symbolic-ref HEAD | sed -e 's!^refs/heads/!!' ) 2>/dev/null`
    if test x"$branch" = x"" ; then
       return
    fi
    echo "$branch "
}
_xterm_short () 
{ 
    printf "\033]1;$LOGNAME@$HOSTNAME\007"
}
_xterm_title () 
{
    printf "\033]2;$LOGNAME@$HOSTNAME: `pwd`\007"
}

if test x"$TERM" = x"xterm" || test x"$TERM" = x"xterm-color" ; then
    PROMPT_COMMAND="_xterm_short;_xterm_title"
fi

The long and short of this it that my terminal windows look like this:

I set all of the ansi_whatever variables in advance to make changing it all easier if I need to. The \[ and \] sequences are very important: they tell bash that the section they surround is non-printing. This comes heavily into play when you edit your command-line, so that the readline library knows where the cursor is. Ignore the \[ and \] delimiters and you start to see weird visual corruption issues when your command lines wrap over more than one line or you recall your history.


blog comments powered by Disqus
Page 1 of 1