Home > Software design >  Current branch in a detached state
Current branch in a detached state

Time:12-18

There are several potential ways to get the name of the current branch:

current-branch1 = name-rev --name-only HEAD
current-branch2 = branch --show-current

The #1 does not work correctly in the presence of tags...

#2 does work better... except when HEAD points to a detached state.

Is there a better alias to know onto which branch the commit was done in a detached state? In other words, one alias that would work better in all cases?

UPDATE -- When checking out a commit, I'd like to get the name of the branch the commit was done onto...

$ g co 2767c5f9
Note: switching to '2767c5f9'.

You are in 'detached HEAD' state. You can look around, make experimental
changes and commit them, and you can discard any commits you make in 
this state without impacting any branches by switching back to a branch.
[...]
HEAD is now at 2767c5f9 Update ChangeLog

$ git for-each-ref --format="%(refname:short)" --points-at HEAD refs/heads

The last command returns nothing...

CodePudding user response:

Yes there is :

# any ref (branch or tag or remote branch or ...)
git for-each-ref --format="%(refname:short)" --points-at HEAD

# branches only :
git for-each-ref --format="%(refname:short)" --points-at HEAD refs/heads

caveat : if several refs/branches point at the current commit, the above commands will list them all.


[edit] git name-rev also has a --refs option, you just have to know that branches are references starting with refs/heads :

git name-rev --name-only --refs="refs/heads/*" HEAD
  • Related