473
votes

Is there a cleaner way to get the short version hash of HEAD from Git?

I want to see the same output as I get from:

 git log -n 1 | head -n 1 | sed -e 's/^commit //' | head -c 8

I originally used the above command to generate a version string, but this is even better:

git describe --tags

It will output strings like 0.1.12 (tagged commit) or 0.1.11-5-g0c85fbc (five commits after the tag).

8
Since you seem to be good at manipulating data with pipes and whatnot, you should know about git aliases. In this case, there is a command for what you want (see answers) but eventually you will find something where there is not, and aliases are great for that. - MatrixFrog
@MatrixFrog thanks for the tip! I already did have some simple git aliases, but I didn't know just how powerful they can be until now. I especially like the graphviz display. - Attila O.
Huh. When I run git describe --tags I get the message, "fatal: No names found, cannot describe anything.". - Quinn Comendant
@QuinnComendant You probably need to tag something first for --tags to work. Try creating a tag first; e.g. git tag 1.0.0. - Attila O.

8 Answers

863
votes

Try this:

git rev-parse --short HEAD

The command git rev-parse can do a remarkable number of different things, so you'd need to go through the documentation very carefully to spot that though.

127
votes

You can do just about any format you want with --pretty=format:

git log -1 --pretty=format:%h 
89
votes
git log -1 --abbrev-commit

will also do it.

git log --abbrev-commit

will list the log entries with abbreviated SHA-1 checksum.

56
votes

A simple way to see the Git commit short version and the Git commit message is:

git log --oneline

Note that this is shorthand for

git log --pretty=oneline --abbrev-commit
36
votes

A really simple way is to:

git describe --always
20
votes

Branch with short hash and last comment:

git branch -v

  develop      717c2f9 [ahead 42] blabla
* master       2722bbe [ahead 1] bla
15
votes

I have Git version 2.7.4 with the following settings:

git config --global log.abbrevcommit yes
git config --global core.abbrev 8

Now when I do:

git log --pretty=oneline

I get an abbreviated commit id of eight digits:

ed054a38 add project based .gitignore
30a3fa4c add ez version
0a6e9015 add logic for shifting days
af4ab954 add n days ago
...
1
votes

what about this :

git log --pretty="%h %cD %cn %s"  

it shows someting like :

674cd0d Wed, 20 Nov 2019 12:15:38 +0000 Bob commit message

see the pretty format documentation enter link description here