Last Updated: February 25, 2016
·
1.86K
· haliphax

Show git branch in bash promt

This .bashrc adjustment was cobbled together from various sources that I cannot remember... my apologies to the original authors for failing to properly cite their effort.

PS1="\$(git branch 2>/dev/null | grep -e '\* ' | sed 's/^..\(.*\)/{\1} /')\u@\h:\w\$ "

5 Responses
Add your response

nice tip alternately you can install bash-it and enable git plugins to so the same.

over 1 year ago ·

I try to avoid installing software on my development machines if I can get away with a script instead -- but I may have to look into this "bash-it"; it sounds interesting. Thanks for the comment!

over 1 year ago ·

do you know how to implement autocomplete on tab (like console file autocompletion) of branch names?

over 1 year ago ·

@axeff My apologies; I do not.

over 1 year ago ·

@haliphax, 'git branch' is human facing ("porcelain") rather than "plumbing". You don't want to rely on parsing git branch output, as it can change. Instead use something like git symbolic-ref -q HEAD.

symbolic-ref includes the refs/heads prefix, so we can strip that off. Also, it'll complain if you aren't in a git managed directory. So, toss the error to /dev/null, then do a variable pattern substitution, and poof: branch name:

branch=${$(git symbolic-ref -q HEAD 2>/dev/null )##refs/heads}

git 1.7.10 added a --short option, that removes refs/heads. Similarly git rev-parse solution:

branch=$(git symbolic-ref -q --short HEAD 2>/dev/null)

branch=$(git rev-parse --symbolic-full-name --abbrev-ref HEAD 2>/dev/null)

zsh shell has a lovely system 'vcs-info' for adding repository information to the prompt, works across multiple source control systems, not just git. Example: http://arjanvandergaag.nl/blog/customize-zsh-prompt-with-vcs-info.html

references: http://stackoverflow.com/questions/1593051/how-to-programmatically-determine-the-current-checked-out-git-branch

over 1 year ago ·