Displaying Git Branch Name with Bash at Command Line
When you’re first introduced to Git, you’ll probably just be working in your master branch, but eventually you’ll want to test some experimental feature in your code base without disturbing the master branch. Git makes this a snap to do with the command “git checkout -b branchname”.
If you’re working on a few experimental features at a time, each with their own branch name, it gets a little confusing as to which branch you’re currently working in. Of course, you could just type in the commands “git branch” or “git status” but there is an easier way to keep track of what branch you’re actively working in.
Robby posted an excellent article titled Lighthouse tickets and Git branching that helps him and others at Planet Argon with their workflow during the day. By appending the Git branch name to the end of the command line prompt, he’s able to instantly recognize which branch he’s currently working in.
Unfortunately, he doesn’t tell you how he achieved that feat. After Googling for a bit, I came up with a solution that worked for me. NOTE: Robby is using the z shell (zsh) and I’m using the built in shell with OS X; bash. My solution works with bash and not zsh.
First, I created a .bash_profile file by running the following command from my home directory: “touch .bash_profile”.
Then I modified the contents of the file to include the following:
function parse_git_branch() {
git branch 2> /dev/null | sed -e '/^[^*]/d' -e 's/* \(.*\)/(\1)/'
}
PS1="\h:\w \u\$(parse_git_branch)$ "
When I’m in a directory that isn’t source controlled via Git, the command line will appear normal:
skyrocket:~ carlos$
Otherwise, it will display the following:
skyrocket:~/work/eddorreblog carlos(master)$
Although I’m using the notation “hostname:working_directory username” you can modify it to your liking using the Bash Prompt HOWTO.