How to Retrieve Hash for Commits in Git
Git allows recovering wrong changes in a project. This tutorial shows how to find information about the latest commit and get the latest commit’s hash.
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.
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 <kbd class="highlighted">git log</kbd> 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 <kbd class="highlighted">--format</kbd> option pretty-prints the contents of the commit logs in a specified format, where ** <format> ** can be <kbd class="highlighted">oneline</kbd>, <kbd class="highlighted">short</kbd>, <kbd class="highlighted">medium</kbd>, <kbd class="highlighted">reference</kbd>, <kbd class="highlighted">email</kbd>, <kbd class="highlighted">full</kbd>, <kbd class="highlighted">fuller</kbd>, <kbd class="highlighted">raw</kbd>, <kbd class="highlighted"> format: <string> </kbd> and <kbd class="highlighted"> tformat: <string> </kbd>. When ** <format> ** is not specified and has <kbd class="highlighted">%placeholder</kbd>, it will act as if <kbd class="highlighted"> --pretty=tformat: <format> </kbd> were specified.
Retrieving the hash
You can use <kbd class="highlighted">git log -1</kbd> to show the information about the latest commit, and from that information, you can get the commit hash by using the <kbd class="highlighted">--format</kbd> option as shown below:
get the latest commit’s hash git
git log -1 --format="%H"
# 2701112aee3d8a7ba13099b1aefec53e1fd3ca3aHere, <kbd class="highlighted">%H</kbd> means <kbd class="highlighted">commit hash</kbd>.
As an alternative, you can use the git-rev-parse command, which will return the hash of the latest git commit:
git rev parse
git rev-parse HEAD
# 2701112aee3d8a7ba13099b1aefec53e1fd3ca3aIf 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 <kbd class="highlighted">cut -c 1-8</kbd> filter in the following way:
git rev-parse to get the first 8 digits of the latest commit hash
git rev-parse HEAD | cut -c 1-8
# 2701112aAlternatively, you can use git rev-parse --short HEAD to get a shortened hash without piping to cut.
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 <kbd class="highlighted">git cherry-pick</kbd>.