Using Git to generate an automatic version number

With one of the most recent projects which clocks in at 6331 lines of code, it becomes difficult to determine whether the production and development versions are running the same version after a number of commits.

The first post I came across, Canonical Version Numbers with Git seemed like a good starting point.

The first thing you need to do is set a tag on your repository:

git tag Prod-1

and we can test to make sure our tag was set:

git describe --tags --long

Now, we create /usr/local/bin/ (as mentioned in one of the comments with a minor change):

revisioncount=`git log --oneline | wc -l`
projectversion=`git describe --tags --long`

echo "$projectversion-$revisioncount"
#echo "$cleanversion.$revisioncount"

You can use either the projectversion or the cleanversion depending on the format you prefer.

The projectversion will contain the sha snippet along with the version and looks like: 1.0-1-g8f63877-291.

The cleanversion removes the sha key leaving 1.0-291.

Now that we’ve got a version number that changes on each commit, we can use this somewhere. This version is updated AFTER the last commit, so, you’ll want to import it into your project somewhere, or, in your commit message.

Before you commit, as one of the commenters in the previous post said, execute: > version

For our footer.mako file, we have the following:

${} ${} ${}
Version: 1.2.3

We now create post-commit in $GIT/hooks:





UP_TO_VERSION="${CONTENTS%%Version:*} Version:"


You can do whatever you need with the post-commit script. I just chose to use bash to rewrite the version number present in the footer of the site. You can just output the version number to a header file that is included if that works with your system.


One Response to “Using Git to generate an automatic version number”

  1. macinnir Says:

    Hey, great post. Really needed to be able to do this. One small (knit-picky) note was that when I run the shell script I was getting a big space between the projectversion and revisioncount variables. To fix, change I changed the following:

    revisioncount=`git log --oneline | wc -l`


    revisioncount=`git log --oneline | wc -l | tr -d ' '`

    This worked like a charm for me. Thanks!

Leave a Reply

You must be logged in to post a comment.

Entries (RSS) and Comments (RSS).
Cluster host: li