I'd like to get the number of commits of my Git repository, a bit like SVN revision numbers.
The goal is to use it as a unique, incrementing build number.
I currently do like that, on Unix/Cygwin/msysGit:
git log --pretty=format:'' | wc -l
But I feel it's a bit of a hack.
Is there a better way to do that? It would be cool if I actually didn't need wc
or even Git, so it could work on a bare Windows. Just read a file or a directory structure...
If you’re looking for a unique and still quite readable identifier for commits, git describe might be just the thing for you.
git rev-parse --short HEAD
Using Bash syntax,
looks fine for purely linear history. If you also want to sometimes have “numbers” from branches (based off
master
), consider:When run from a checkout of
master
, you get simply1234.0
or the like. When run from a checkout of a branch you will get something like1234.13
, if there have been 13 commits made on that branch. Obviously this is useful only insofar as you are basing at most one branch off a givenmaster
revision.--first-parent
could be added to the micro number to suppress some commits arising only from merging other branches, though it is probably unnecessary.To get it into a variable, the easiest way is:
If you're just using one branch, such as master, I think this would work great:
This will only output a number. You can alias it to something like
to make things really convenient. To do so, edit your
.git/config
file and add this in:This will not work on Windows. I do not know the equivalent of "wc" for that OS, but writing a Python script to do the counting for you would be a multi-platform solution.
git rev-list HEAD --count
git rev-list
git rev-list <commit>
: List commits that are reachable by following the parent links from the given commit (in this case, HEAD).--count
: Print a number stating how many commits would have been listed, and suppress all other output.