Raine Revere
Raine Revere

Reputation: 33775

git: How do I get the hash of the latest commit in the current branch when in detached HEAD state?

How do I get the hash of the latest commit...

  1. when in detached HEAD state
  2. without specifying the branch explicitly

git rev-parse HEAD and git log -n 1 --format="%H" both follow the detached HEAD (obviously).

git rev-parse master has me typing in the branch.

I'm guessing that the detached HEAD state has no notion of branches, but do you see my intention? I've been in master the whole time so I don't want to have to specify it explicitly just because I'm looking at a previous commit.

Same as this question but for detached HEAD state.

Thanks!

Upvotes: 1

Views: 1225

Answers (2)

jthill
jthill

Reputation: 60547

To refer to "the n‍th previous branch I checked out", use @{-n}.

git rev-parse @{-1}

This really is a branch reference:

git checkout @{-1}

will leave you on that branch.

Upvotes: 0

Wolf
Wolf

Reputation: 4462

A problem is that the commit you are on (detached from the head) may actually be on several branches. If you only want one branch to be presented, you'll have to figure out some way to choose between them. But if you're happy seeing all the branches (with hashes) that contain your current commit you can say

git branch -v --contains HEAD

Here's some example output:

* (detached from 0bc85ab) 0bc85ab Git 1.9.2
  master                  cc29195 Git 2.0-rc0

you could trim that with grep and/or awk.

Upvotes: 2

Related Questions