Tag Archives: git

Current git branch in shell prompt

Since I”ve read much about git and how great it is, I recently thought that I had to try it myself. And indeed, it is quite amazing and is nice to work with. There was one thing that I disliked, though: I never quite knew in which branch of my repository I was, especially after I”ve been away from coding for a few hours.
Of course I could just look that up, but I tend to forget that and then end up with code that belongs to a different branch. Now the shell prompt looked like a good place to show the current branch, but simply executing “git branch | grep ^*” would only work in the top-level directory of the repository. So I wrote the following function which will traverse all containing directories and look for a .git directory. Having found one, it will nicely print the the branch in dark green color, with a @ sign in front of it:

Update: As many people have pointed out, bash-completion provides a function called __git_ps1 which will happily print the current git branch and can be used as well. I don”t quite like the rest of bash-completion, though, so I”ll stick with my own.
As Yuri pointed out, git branch works from any directory, so here”s the updated (and much shorter 🙂 ) version:

Having this in my .bashrc, I could integrate it quite nicely with my prompt:

git prompt