4

Scripting git, I need to find out the checked-out branch name. So far it seems the only "reliable" way to do that is with git branch | sed -n '/^\* /s///p'. (Scare quotes because of things like color.branch or column.branch in .gitconfig; it's not reliable at all.) The only other thing I found is git name-rev, but that seems to return the first (sorted by names) branch that points to HEAD:

> git checkout master
> git checkout -b another
> git checkout master
> git name-rev HEAD
HEAD another

Is there something better than sed -n '\#^ref: refs/heads/#s###p' .git/HEAD to figure out the checked out branch?

just somebody
  • 18,602
  • 6
  • 51
  • 60
  • Seems similar to http://stackoverflow.com/questions/1593051/how-to-programmatically-determine-the-current-checked-out-git-branch – Travis Pessetto May 31 '13 at 13:32

2 Answers2

9

Just output the branch you are on with:

git rev-parse --symbolic-full-name --abbrev-ref HEAD

There should be no trouble also if you have more than one branches, and if you aren't on any branch it just gives you HEAD

bpoiss
  • 13,673
  • 3
  • 35
  • 49
  • Both this and twalberg's answers are correct for the question as stated and I've upvoted both of them. If it was possible to accept multiple answers, I would do it in this case. `git symbolic-ref` won because I prefer non-zero exit code for detached HEAD. Unstated requirements, I know. – just somebody Jun 01 '13 at 07:45
6

Here's a little git invocation I've used in a couple of scripts, that either gives back refs/heads/branchname, or if you're not on a branch, it gives the SHA of your detached HEAD:

cur_branch=$(git symbolic-ref HEAD 2>> /dev/null || git rev-parse HEAD)

Removing the refs/heads/ prefix should be pretty simple, if you need it...

twalberg
  • 59,951
  • 11
  • 89
  • 84