Hi! Please consider following me on twitter: @hanekomu.

Current git branch in the bash prompt

You can use git branch to see the branch you're currently in, but it's easy to forget and to commit something into the wrong branch.

I wanted to have a constant reminder, so I chose to display the current branch on the bash prompt.

function parse_git_branch {
   ref=$(git symbolic-ref HEAD 2> /dev/null) || return
   printf " (${ref#refs/heads/})"
}

export PS1="\$(parse_git_branch) \$ "

The first backslash in PS1 is important so the function gets evaluated for every new bash prompt. If you're not inside a git repository, nothing will be printed. Let's see this in action.

 $ git init
Initialized empty Git repository in /path/to/repo/.git/
 (master) $ git checkout -b newbranch
Switched to a new branch 'newbranch'
 (newbranch) $ git checkout master
Switched to branch 'master'
 (master) $ cd ~
 $ 

This is just a bare shell prompt and actually I have a rather "baroque" PS1 setting, but that's for another blog post.

Write a comment | Bookmark and Share

posted at: 18:41 | path: /misc | permalink | 1 comment | 0 trackbacks

Pedro Melo wrote at 2010-07-16 22:43:

Hi,

git includes a bash-completion script and inside there is a bash prompt function that is a lot more complete that that.

I wrote about this some time ago: http://www.simplicidade.org/notes/archives/2008/02/git_bash_comple.html

Comments are closed for this story.

Trackbacks are closed for this story.