Home > Development, Linux > my git prompt

my git prompt

May 26th, 2010

After long playing around with my prompt I finally made it stable and thought it’s time to share :)

So edit your ~/.bashrc file and add following lines on the end:

shopt -s promptvars dotglob histappend no_empty_cmd_completion cdspell xpg_echo

function parse_git_dirty {
  echo -n $(git status 2>/dev/null | awk -v out=$1 -v std="dirty" '{ if ($0=="# Changes to be committed:") std = "uncommited"; last=$0 } END{ if(last!="" && last!="nothing to commit (working directory clean)") { if(out!="") print out; else print std } }')
}
function parse_git_branch {
  echo -n $(git branch --no-color 2>/dev/null | awk -v out=$1 '/^*/ { if(out=="") print $2; else print out}')
}
function parse_git_remote {
  echo -n $(git status 2>/dev/null | awk -v out=$1 '/# Your branch is / { if(out=="") print $5; else print out }')
}
export PS1='$(ppwd \l)\u@\h:\[33[33m\]\w\[33[0m\]$(parse_git_branch ":")\[33[36m\]$(parse_git_branch)\[33[0m\]$(parse_git_remote "(")\[33[35m\]$(parse_git_remote)\[33[0m\]$(parse_git_remote ")")\[33[0m\]$(parse_git_dirty  "[")\[33[31m\]$(parse_git_dirty )\[33[0m\]$(parse_git_dirty  "]")>'

I know it looks a bit complicated, unfortunately it is … this is wired bash rule that escape sequences are evaluated before evaluation of functions/variables evaluation.

Some examples of prompt using this script:

mpapis@papis:~/old_laptop/nicz-projects/content2:master> touch a
mpapis@papis:~/old_laptop/nicz-projects/content2:master[dirty]> git add .
mpapis@papis:~/old_laptop/nicz-projects/content2:master[uncommited]> git commit -m "added a file"
mpapis@papis:~/old_laptop/nicz-projects/content2:master(ahead)>git push origin master
mpapis@papis:~/old_laptop/nicz-projects/content2:master>

To make it more useful the prompt is also colored to distinguish between states of git repo.

For lazy users the script could be also replaced by very easy version, which prints git status before each prompt line (only where git is applicable):

export PS1='$(git status 2>/dev/null)\[33[0m\]\n$(ppwd \l)\u@\h:\[33[33m\]\w\[33[0m\]>'

Note: download the code from here http://niczsoft.com/files/2010/05/my-git-prompt.txt

Categories: Development, Linux Tags: , ,
  1. May 29th, 2010 at 00:38 | #1

    I know it, it misses the dirty/uncommited functionality, and the dirty was starting point for me.

  2. May 28th, 2010 at 00:17 | #2

    OR if u have git >= 1.6.0 (at least in debian package_ there is cute lil’ function loaded by default named “__git_ps1″, just add $(__git_ps1) to ur PS1.

    It shows actual branch, and if ure merging/rebasing/bisecting

Comments are closed.