To obtain the hash of the current commit in Git, use one of the following commands:
1. Full Commit Hash
git rev-parse HEAD
- Output: The full 40-character SHA-1 hash (e.g.,
d0a1b2c3d4e5f6a7b8c9d0e1f2a3b4c5d6e7f8a9
). - Purpose: Directly retrieves the hash of the commit where
HEAD
is pointing.
2. Shortened Commit Hash
git rev-parse --short HEAD
- Output: A shortened 7-character hash (e.g.,
d0a1b2c
). - Use Case: Useful for compact references in logs or UIs.
Alternative Methods (Same Result)
Using git log
:
git log -1 --pretty=format:%H
-1
: Show only the latest commit.%H
: Format placeholder for the full hash.
Using git show
:
git show -s --format=%H
-s
: Suppress diff output.%H
: Format placeholder for the full hash.
Key Notes
- HEAD: Refers to the current commit (works even in “detached HEAD” state).
- Edge Cases:
- Fails in a new repository with no commits (no
HEAD
exists). - Always returns the hash of the commit checked out in your working directory.
Example Output
$ git rev-parse HEAD
d0a1b2c3d4e5f6a7b8c9d0e1f2a3b4c5d6e7f8a9
$ git rev-parse --short HEAD
d0a1b2c