Jan Warchoł
Jan Warchoł

Reputation: 1129

How to get current state of HEAD in git?

For example, if I'm on a branch, I want to get the branch name. But if I'm in detached HEAD state, I want to get the commit id.

Basically, I'm looking for an interface to .git/HEAD file. I know I could just cat it, but maybe there's a command that will do that for me (so that I won't have to handle edge cases like GIT_DIR not being inside GIT_WORK_TREE etc.)

Upvotes: 1

Views: 2059

Answers (1)

Sardorbek Imomaliev
Sardorbek Imomaliev

Reputation: 15370

If you are using git completion https://github.com/git/git/blob/master/contrib/completion/git-completion.bash. Which is usually automatically installed.

You could call

echo $(__git_ps1 '%s')

Otherwise use.

git symbolic-ref --short HEAD 2> /dev/null || git rev-parse HEAD

Upvotes: 6

Related Questions