Git

How to Get the Hash for the Current Commit in Git?

A hash is a unique commit id generated automatically and assigned to commits whenever a new commit is created. It is used while merging different commits or finding differences between commits. More specifically, Git provides various commands to get the hash of the most recent commit or all commits.

This article will discuss different methods to get the commit id in Git:

Method 1: Get the Commit ID in Git Using the “git rev-parse HEAD” Command

To get the full SHA-hash value of the latest commit in the repository, utilize the “git rev-parse HEAD” command. To do so, follow the provided steps.

First, redirect to desired local Git repository:

$ cd "C:\Git\Repo3"

Then, execute the below-provided command:

$ git rev-parse HEAD

Here, the “rev-parse” command prints the SHA-hash of the current position of the HEAD:

Method 2: Get the Commit ID in Git Using the “git show -s” Command

To get the latest commit hash along with all required information, run the “git show -s” command. Here, the “-s” flag is used to get the information of the most recent commit:

$ git show -s

The output below displays all the commit information, including the commit hash, the position of HEAD, and the commit message:

Method 3: Get the Commit ID in Git Using “git log” Command

Execute the following command to get the detailed information, including the SHA-hash of all commits as well as the current commit in the repository:

$ git log --oneline

It can be observed that the hashes of all commits that have been made in the current working repository along with their commit messages have been displayed:

Note: If the developer wants to get the information about the latest commit only, then use the “-1” range with “git log” command:

$ git log -1

Here, “-1” range is used to only display the information of the most recent commit:

Method 4: Get the Commit ID in Git Using the “git reflog” Command

If you want to find the commit hash along with the history on the head of branches, then execute the below-provided command:

$ git reflog

That’s it! We have explained all the possible ways to get the hash for the current commit in Git.

Conclusion

Multiple commands are available to retrieve the commit SHA-hash in Git, such as “git rev-parse HEAD” for getting full SHA-hash. If you want to get the full details of the most recent commit id, the “git show -s” or “git log -1” commands can be used. To get the SHA-hash and commit message along with the head index value, execute the “git log –oneline” and “git reflog” commands. This article explained the methods of getting the hash of the current commit in Git.

About the author

Sharqa Hameed

I am a Linux enthusiast, I love to read Every Linux blog on the internet. I hold masters degree in computer science and am passionate about learning and teaching.