Since I am using the git bash prompt during my daily development tasks on Icinga & other stuff, I’m getting used to the git branch shown in my bash prompt. Sadly there was a bug in my previous configuration on parsing the git branch output, causing funny whitespace pingpong games on the shell (quite annoying tbh).

Lazyfrosch always suggested me his version, but tbh I’ve got some rules on my shell that I follow quite strictly:

  • one line to rule them all
  • user@hostname and hostname only when root
  • root is red, user is green (thanks tebe!)
  • root got #, user gets $
  • if this is a git repo, show branchname at the end

So I’ve reworked my existing version using the ideas by Markus into my very own function, fitting for both users and root, git or non-git repo and still one line.

Even further, having the package bash-completion installed, we can simply use $(__git_ps1) in order to simply get (branch) (no trickery with formatting than colors needed).

Looks like

bash_prompt_git_user

bash_prompt_git_root

# apt-get install bash-completion

… and the entries for .bashrc look like

# =========================================================
# COLOR PROMPTS WITH GIT BRANCH
# =========================================================
function myPrompt() {
        local GREEN_BOLD="[33[01;32m]"
        local RED_BOLD="[33[01;31m]"
        local BLUE_BOLD="[33[01;34m]"
        local GREEND="[33[02;32m]"
        local REDD="[33[02;32m]"
        local DEFAULT="[33[00m]"

        # h ... hostname
        # w ... workdir
        # $? ... RC
        # u ... user
        # $(formattedGitBranch) ... git branch if available

        local USER_BOLD=$GREEN_BOLD
        local USERD=$GREEND
        local USERAT="u@h"
        local USERHASH="$"

        if [ `/usr/bin/whoami` = 'root' ]
        then
                USER_BOLD=$RED_BOLD
                USERD=$REDD
                USERAT="h"
                USERHASH="#"
        fi

        PS1="$USER_BOLD$USERAT$DEFAULT $BLUE_BOLDw$DEFAULT"
        PS1=$PS1"$DEFAULT$GREEND$(__git_ps1)$BLUE_BOLD $USERHASH $DEFAULT"

        # window title
        case "$TERM" in
                xterm*|rxvt*)
                        PS1="[e]0;h: w (u)a]$PS1"
                        ;;
        esac
}

# set git colored prompt based on uid
myPrompt

Update 2013-08-16: On systems without git bash completion installed (ie CentOS 6), you may use the following trick:

# curl https://raw.github.com/git/git/master/contrib/completion/git-prompt.sh > ~/.bash_git
# vim .bashrc
source ~/.bash_git

# . .bashrc
%d bloggers like this: