Joined July 2011
·

Andrew Grangaard

Open 42
·
Santa Monica, CA
·
·
·

Posted to Show git branch in bash promt 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

Achievements
79 Karma
0 Total ProTip Views