code-8
code-8

Reputation: 58632

How to get the commit hash (ID) from specific commit count?

enter image description here

Each time we committed, that consider as a count. You can check your current commit count by running this command:

git log --pretty=format:'' | wc -l


100th

Let's assume, I want to get the commit-id of my 100th commits.

Is there a way to get the commit id base on that count?

Upvotes: 1

Views: 1476

Answers (3)

torek
torek

Reputation: 487755

You've drawn your commits as being all in a nice neat straight line.

This does sometimes happen, but in most real repositories, there are sections of commits that are not in a nice neat straight line:

...--A--B--D---------H--I--J   <-- newest
         \          /
          C--E--F--G

Let's say we want commit I. This is easy to find: it's one step back from commit J. Using:

git rev-parse newest~1

will find commit J. Similarly, to find commit H, we can go back two steps:

git rev-parse newest~2

will print the hash ID of commit H.

But commit G is two steps back, then one step down-and-back. Commit D is three steps back in a straight line. This happens because commit H is a merge commit.

Assuming commit D is the first parent of commit H, writing:

git rev-parse newest~3

will find its hash ID. Git will step back three times, along the first-parent line. There's only one parent of J and only one of I so the first parent is the only parent, but at H, the first-parent specifically chooses D and not G.

If you use git log or git rev-list, both of these must display the commits linearly. The method they use to do this is rather tricky, and the order that commits show up, in this output, is affected by command-line options: --author-date-order, --topo-order, and so on.

If you're satisified with the order that git rev-list (or git log) uses on its own, use Rakmo's answer. (Remember that git log and git rev-list work backwards, from the newest towards the oldest. You can have them reverse their output with --reverse but this interacts weirdly with --skip. You might want to just get a complete list of commits, reverse it, and pick the n'th line of that.)

If you would like to traverse first-parents only, and want to count from the end—that is, newest names the newest, newest~1 names the commit one step back, and so on—use Daniel A. White's answer or some variant of it.

For more complex answers to what turns out to be a complex question (if you aren't satisfied with Git's default linearization, that is), you'll need to refine the question.

Upvotes: 1

Rakmo
Rakmo

Reputation: 1982

git log -1 --skip=n

will skip the first n-commits, and just show 1 commit

To just get the ID:

git log -1 --skip=n --pretty=format:"%h" --no-patch

Where in your case n=100

Upvotes: 3

Daniel A. White
Daniel A. White

Reputation: 190897

You can also do git show HEAD~n --format=oneline to just get the one commit.

Upvotes: 1

Related Questions