Thursday, April 16, 2015

Add git branch name to bash prompt

When working with git branches I found it helpful if the branch was displayed in my terminal itself rather than me having to cross check
In both the approaches all we have to do is add the piece of code to our .bashrc and source it.

Steps : 

  1. Open your .bashrc file with your favorite editor
  2. gedit ~/.bashrc
    
  3. Copy and paste code snippets of any one approach
  4. source the .bashrc file
  5. source ~/.bashrc 
     

Approach 1 :


function parse_git_branch () {
  git branch 2> /dev/null | sed -e '/^[^*]/d' -e 's/* \(.*\)/ (\1)/'
}

RED="\[\033[0;31m\]"
YELLOW="\[\033[0;33m\]"
GREEN="\[\033[0;32m\]"
NO_COLOR="\[\033[0m\]"
LBLUE="\[\033[0;94m\]"
LMAGENTA="\[\033[0;95m\]" 
 
# Use a color you like PS1="$LMAGENTA\u@\h$NO_COLOR:\w$LBLUE\$(parse_git_branch)$NO_COLOR\$ "

Approach 2:

function _git_prompt() {
    local git_status="`git status -unormal 2>&1`"
    if ! [[ "$git_status" =~ Not\ a\ git\ repo ]]; then
        if [[ "$git_status" =~ nothing\ to\ commit ]]; then
            local ansi=42
        elif [[ "$git_status" =~ nothing\ added\ to\ commit\ but\ untracked\ files\ present ]]; then
            local ansi=43
        else
            local ansi=45
        fi
        if [[ "$git_status" =~ On\ branch\ ([^[:space:]]+) ]]; then
            branch=${BASH_REMATCH[1]}
            test "$branch" != master || branch=' '
        else
            # Detached HEAD.  (branch=HEAD is a faster alternative.)
            branch="(`git describe --all --contains --abbrev=4 HEAD 2> /dev/null ||
                echo HEAD`)"
        fi
        echo -n '\[\e[0;37;'"$ansi"';1m\]'"$branch"'\[\e[0m\] '
    fi
}
function _prompt_command() {
    PS1="`_git_prompt`"'\[\e[1;34m\]\w \$\[\e[0m\] '
}
PROMPT_COMMAND=_prompt_command 
 

No comments: