How to Retrieve Hash for Commits in Git

  1. Retrieving the hash
  2. The git log Command
  3. The --format Option

The git log command is used for listing and filtering the project history and searching for particular changes. Let's figure out how you can retrieve hash for commits below.

Retrieving the hash

You can use git log -1 to show the information about the latest commit, and from that information, you can get the commit hash by using the --format option as shown below:

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

Here, %H means commit hash.

As an alternative, you can use the git-rev-parse command, which will return the hash of the latest git commit:

git rev-parse HEAD
If you want to turn references (branches and tags) into hash, you can use git show-ref and git for-each-ref commands.

In case you want to get only the first 8 digits, you can use the cut -c 1-8 filter in the following way:

git rev-parse HEAD | cut -c 1-8

Using the git reflog command is also used 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. After getting the hash of the commit you can restore it by using git cherry-pick.

The git log Command

The git log command displays the committed snapshots. It only works on the committed history, whereas git status controls the working directory and the staging area.

The git log command examines a repository’s history and finds a particular version of a project. Log output can be personalized differently, from filtering commits to displaying them in an entirely user-defined format.

The --format Option

The --format option pretty-prints the contents of the commit logs in a specified format, where <format> can be oneline, short, medium, eference, email, full, fuller, raw, format:<string> and tformat:<string>. When <format> is not specified and has %placeholder, it will act as if --pretty=tformat:<format> were specified.


Do you find this helpful?

Related articles