Skip to main content

How to Get the Current Commit Hash with git rev-parse HEAD

· 3 min read
Jagdish Kumawat
Founder @ Dewiride

Every Git commit has a hash, a long ID that names exactly that version of your code. Scripts, build tools and experiment trackers record it so you can always get back to the code that produced something. git rev-parse HEAD prints the hash of the commit you're on. This guide prints it in full and short, with real output from Git 2.56.

Syntax​

Syntax
git rev-parse [--short] HEAD
PartWhat it means
rev-parseTurns a name for a commit into its hash
HEADThe commit you're on. Git's documentation: "HEAD names the commit on which you based the changes in the working tree."
--shortOptional. Prints the start of the hash instead, as long as it stays unique

Git's rev-parse documentation on --short: "shortens the object name to a unique prefix with at least length characters."

The Example​

A folder called git-demo with one commit, Start the notes.

Prerequisites​

  • Git. This guide uses Git 2.56.1.

Step 1: Print the Full Hash​

In the repository's folder:

Terminal
git rev-parse HEAD
Output
aeeba335fad83a133d5152af30a85daa4e4f79f9

Forty characters: the full hash of the commit the repository is at.

Step 2: Print the Short Hash​

Terminal
git rev-parse --short HEAD
Output
aeeba33

The start of the same hash, the form Git shows in its own lists:

Terminal
git log --oneline
Output
aeeba33 (HEAD -> main) Start the notes

A terminal running git rev-parse HEAD, git rev-parse --short HEAD and git log --oneline: aeeba335fad83a133d5152af30a85daa4e4f79f9, aeeba33, and aeeba33 (HEAD -> main) Start the notes.

Common Mistakes​

MistakeWhat happensDo this instead
Recording the hash before committing your changesThe hash names the last commit, which doesn't have themCommit first, then read the hash
Storing the short hash for the long termA short hash is unique only among the commits that exist nowStore the full hash, and show the short one

Troubleshooting​

SymptomLikely causeFix
fatal: not a git repository (or any of the parent directories): .gitThe folder isn't inside a Git repositoryRun it in the repository's folder

FAQ​

Does the hash change when I edit a file?​

No. It changes when you commit. Until then, git rev-parse HEAD prints the last commit's hash.

Can I get the hash from inside a program?​

Yes: run git rev-parse HEAD from the program and read what it prints. Python's subprocess.run does that, for example.

Conclusion​

git rev-parse HEAD printed aeeba335fad83a133d5152af30a85daa4e4f79f9, the commit the repository is at, and --short printed aeeba33, the same start git log --oneline shows.

Additional Resources​