1

I need a git command that returns the name of the branch to which HEAD points. I.e., when I am on master, it should return master. In detached HEAD state, it can return either nothing or something that I will not confuse with a branch name. What is the easiest command to achieve this?

(Sorry, the question seems to be rather trivial and was probably asked a gazillion of times, but searching for things like "get branch to which HEAD points" didn't give me a satisfying result.)

gexicide
  • 38,535
  • 21
  • 92
  • 152

2 Answers2

3

You are probaply looking for:

  • git symbolic-ref --short HEAD
  • git rev-parse --abbrev-ref HEAD

But it's also possible to manually read .git/HEAD

MrTux
  • 32,350
  • 30
  • 109
  • 146
  • 2
    These are the two best ways to do this from a script. There is an important difference between them: the `git symbolic-ref` command fails (with an error message) if your HEAD is "detached", while the `git rev-parse --abbrev-rev` command prints `HEAD` for this case. So if you want `HEAD` printed for this case, use `git rev-parse`; if you want to check, and use a different code path for detached HEAD, use `git symbolic-ref`. – torek Jun 30 '17 at 14:47
0

Run this command to add an alias to git config.

git config --global alias.current "!git branch|grep '*'"

git current # should return the name of current branch.

Note: You can use git symbolic-ref --short HEAD too instead of grep to find the current branch as @MrTux suggested.

hspandher
  • 15,934
  • 2
  • 32
  • 45