21

I am using below git command to get last 2 commit hash

git log -n 2 --pretty=format:"%H"  #To get only hash value of commit

But I needs only second last commit hash.

Any help would be great

Thanks

3 Answers3

36
git rev-parse @~

rev-parse turns various notations into hashes, @ is current head, and ~ is the previous commit.

This generalizes to commits arbitrarily far back: for example, you can write @~3 (or @~~~) to specify "three commits before the current head".

amalloy
  • 89,153
  • 8
  • 140
  • 205
  • 2
    I think one crucial thing is missing here: the revision selector `@~` also accepts a number after the `~`, e.g. `@~3` means: the parent (`~`) of the parent of the parent (`3` times) of HEAD (`@`). ([see git documentation](https://git-scm.com/book/en/v2/Git-Tools-Revision-Selection#_ancestry_references)) – Gerrit-K Aug 10 '18 at 07:17
  • @Griddo should probably edit that in, as that is _insanely_ helpful. – Tom Granot Jun 13 '19 at 10:20
  • 1
    Fair enough, @t0mgs. Not strictly necessary in a question about "the previous commit", but people might well get here looking for some other previous commit. – amalloy Jun 13 '19 at 18:33
  • @amalloy i.e. moi, for example! :) – Tom Granot Jun 13 '19 at 20:32
  • I prefer to use `HEAD` with index. i.e. to **last commit** I would use `git rev-parse HEAD~0`, to **penultimeate commit** `git rev-parse HEAD~1`, etc. – ferpaxecosanxez May 11 '22 at 13:32
21

Use skip attribute
--skip=<number> skips number commits before starting to show the commit output.

git log -n 1 --skip 1 --pretty=format:"%H"

Follow this link for more info on git log

Ashwani
  • 1,938
  • 11
  • 15
4

You can just pipe the output of your command through tail:

git log -n 2 --pretty=format:"%H" | tail -1
Paul R
  • 208,748
  • 37
  • 389
  • 560