How to Get the Current Commit Hash in Git


How can we get the hash for the current commit in Git?

Using rev-parse

We can obtain the hash using rev-parse.

git rev-parse HEAD
git rev-parse --verify HEAD # Using verify flag

We can add the --verify flag to rev-parse to ensure that the specified object is a valid git object.

It’s especially help to use it --verify with a variable branch name.

git rev-parse --verify $branch

To obtain the shortened version of the hash, we can use the --short flag.

git rev-parse --short HEAD

Using git log

We can obtain the commit hash of the current commit using git log as well.

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