Pages

Friday, September 3, 2010

Add git branch to bash prompt

If you use git, you will find this small trick very useful.

To make your bash prompt super spiffy (and equally useful), add this to ~/.bashrc:

 #Adding git branch to command prompt
 gitStatus() { git diff --quiet 2> /dev/null || echo ' *' ; }
 gitBranch() { git branch --no-color 2> /dev/null | sed -e '/^[^*]/d' -e "s/* \(.*\)/ > \1$(gitStatus)/" ; }

Then, somewhere in your $PS1, put \$(gitBranch). Here's an example; try it:

      export PS1="[\u@\h$ \w\$(gitBranch)]\$ "

When you're in a git directory, you'll notice the branch name on the prompt. If the branch has been modified, an asterisk will appear next to the name. Here is an example :

My command prompt looks like this - 

cdump@cdump-linux : /workspace/android/platform > cros-wm *$

indicating I am on cros-wm branch and there are modified files.

Git-goodness!
Credit Serban Giuroiu

8 comments:

  1. Someone seems to have become a git goddess. I still remember our struggles with git. And yeah... "what a GEEK"

    ReplyDelete
  2. I kinda of mostly remember my branch - and an occasional git status or git branch doesn't hurt
    Useful - when i start having a lot of branches.
    I find git autocomplete commands more useful though :)

    ReplyDelete
  3. @Sastry, I have no choice and I am still afraid of git :P

    @rohit I agree autocomplete is useful.
    I often switch workspace so branch-name on prompt becomes handy.

    ReplyDelete
  4. This blog is very inspiring to me. With pleasure I will recommend this blog to my friends.

    ReplyDelete