How to Retrieve Hash for Commits in Git

You can use git log -1 to show the information about the latest commit and from that information you can use grep to get the hash.

A better method for getting the latest commit’s hash in Git is using the --format option of git log:

git log -n1 --format=format:"%H"

Here, “%H” means “commit hash”.

To get the latest git commit SHA-1 hash ID, use the git-rev-parse command like this:

$ git rev-parse HEAD
or
$ git rev-parse --verify HEAD

Note if you want to turn references (branches and tags) into SHA-1, you can use git show-ref and git for-each-ref commands.

In the case you want to get only the first 8 digits, use $ git rev-parse HEAD | cut -c 1-8 where the cut -c 1-8 gives 1 to 8 bytes.

Using $ git reflog command is also a good way if you want to have the history on the head of your branches. With this command you can find the line referring to the state you want to get back to. Knowing the hash of the commit, you can restore it by using $ git cherry-pick with your hash and restore it.