55
votes

I want to build JAR with self-defined version passed via command line, such as:

When I execute gradle build task like this:

gradle build -Pversion=1.0

myproject-1.0.jar should be generated.

I have tried adding the line below to the build.gradle, but it did not work:

version = project.hasProperty('version') ? project['version'] : '10.0.0'
7
Have you tried with adding system property (-D) instead of project property (-P)? - Misa Lazovic
@MisaLazovic It did not work either. - pat.inside
Stupid thing, but try with format gradle [option] [task], not gradle [task] [option], i.e. try gradle -Pversion=1.0 build. Any luck? - Misa Lazovic
@MisaLazovic Did not work. I do not think reading project or system property is the problem, because it can be read in my other tasks. I think there is something wrong when the build task executing, maybe the build task cannot dynamic read the version? - pat.inside
@MisaLazovic Sorry I try system property again, it works! But why project property does not work? - pat.inside

7 Answers

102
votes

Set the property only in the gradle.properties file (i.e. remove it from build.gradle). Also make sure the options come before the command (as mentioned above).

gradle.properties contents:

version=1.0.12

Version can then be overridden on the command line with:

gradle -Pversion=1.0.13 publish
37
votes

You are not able to override existing project properties from command line, take a look here. So try to rename a version variable to something differing from version and set it with -P flag before command, like:

gradle -PprojVersion=10.2.10 build 

And then in your build.gradle

if (project.hasProperty('projVersion')) {
  project.version = project.projVersion
} else {
  project.version = '10.0.0'
}

Or as you did with ?: operator

15
votes

If you move version entry to gradle.properties file you can also:

gradle clean build -Dorg.gradle.project.version=1.1
8
votes

If you need a default version other than 'unspecified':

version = "${version != 'unspecified' ? version : 'your-default-version'}"

Pass version via command line:

gradle build -P version=1.0
7
votes

You can pass the project version on cli with -Pversion=... as long as you don't set it in build.gradle. If you need a custom default value for when no version is passed on the cli, use gradle.properties file like so: version=...

TL;DR: Don't set the version in build.gradle file if you want to change it later on via cli.

4
votes

version = (findProperty('version') == 'unspecified') ? '0.1' : version

0
votes

I've found this to be the easiest and cleanest way, without requiring a gradle.properties file or changing the version variable name.

In build.gradle:

// Note - there is intentionally no equals sign here
version project.hasProperty('version') ? version : '1.0.0'

From the command line:

./gradlew -Pversion=1.5.2 build