How to retrieve the hash for the current commit in Git

Overview

Git is an open-source and free distributed version control system.

In this shot, we learn how to retrieve the hash for the current commit in Git. We do this using the following Git command:

$ git rev-parse HEAD

Example

Let's see an example.

# Create folder
$ mkdir example
# Move to that folder
$ cd example
# Create a file and write content with the command
$ echo "This is a test file" | tee test.txt
# Set a dummy username and email
$ git config --global user.email "example@example.com"
$ git config --global user.name "example"
# Initiate git
$ git init
# Add all files in the current folder to git
$ git add .
# Create a commit
$ git commit -m "Added test file"
# Get the hash code for the latest commit
$ git rev-parse HEAD

Explanation

We follow these steps in the example above:

  • We make a directory example and create a file in it.
  • We initialize a Git repository, add the created file, and then commit it.
  • Finally, we get the hash of the last commit using the git rev-parsecommand.

We can see the hash for the latest commit in the terminal below.

Terminal 1
Terminal
Loading...

Free Resources