How to increment build numbers during continuous integration, only

Forgive me if this has already been asked but searching for things like “increment build number” returns a flood of “incremental build” topics.

I’m looking for the ideal way to increment a build number in our Android app, only when the build runs on Jenkins. All of our devs build on Macs, while none of our Continuous Integration servers are Macs. So I’m thinking of logic like:

if( isBuildServer() ) incrementBuildNumber()

But there are dozens of ways to approach this and I wanted to get a more authoritative opinion on the best approach. This is what I came up with and it works but there are several problems. For instance, attaching the task to “clean” just feels wrong (even thought the build server only runs “clean” once for each build) but with the Android plugin, I couldn’t think of any better phase to use that works for all product flavors/groups/buildTypes

//only responds to versionNames such as "3.0.2 build 584", "3.0.2 build: #584", "3.0.2 BuildNumber 584", etc.
def replaceVersion = { text ->
    text.replaceFirst(/(android:versionName\s*=\s*"[^"]*[bB]uild\D*)([\d]+)(?! ")/, {
        it[1] + it[2].toInteger().plus(1)
  def isBuildServer = {
  task incrementBuildNumber(group: "Build",
                          description: "Increments the build number in the Android Manifest") << {
      def manifestFile = android?.sourceSets?.main?.manifest?.srcFile
    if(!manifestFile?.exists()) return
  incrementBuildNumber.onlyIf{ isBuildServer() }
clean.dependsOn incrementBuildNumber

Any advice on a more ideal approach to this somewhat common problem?

I would pass an argument “-PincrementBuildNumber”, then check ‘hasProperty(‘incrementBuildNumber’)’. This way, it isn’t much problem to increment it during script evaluation time.

I did it like this: Most ci:s have some form of “build number” concept… Let the build server build with an extra -PappendBuildNumber= and use this number in your versioning scheme. I find it useful to have a “soft” link between ci-builds an produced binaries. Aka you know that version 1.3.89 was built by ci build number 89 for you project.