How to extract version from build.gradle to a Jenkins pipeline

Viewed 2516

I'm trying to extract my app version from the build.gradle, but I'm not arriving as I want.

On my build.gradle I have several properties and the one I want:

version = '1.4.1-SNAPSHOT'

So, on my Jenkinsfile I did:

def version_value = sh(returnStdout: true, script: "cat build.gradle | grep -o 'version = [^,]*'").trim()
sh "echo Project in version value: $version_value"
def version = version_value.substring(0, version_value.indexOf('='))
sh "echo final version: $version"

And I'm getting the following error:

+ cat build.gradle
+ grep -o version = [^,]*
[Pipeline] sh
[QR_CODE_GATEWAY] Running shell script
+ echo Building project in version value: version = 1.4.1-SNAPSHOT
Project in version value: version = 1.4.1-SNAPSHOT
+ version = 
/var/jenkins_home/workspace/PROJECT@tmp/durable-bbc0290d/script.sh: 3: /var/jenkins_home/workspace/PROJECT@tmp/durable-bbc0290d/script.sh: version: not found
[Pipeline] }
[Pipeline] // stage
[Pipeline] }
[Pipeline] // node
[Pipeline] End of Pipeline
ERROR: script returned exit code 127
Finished: FAILURE

I appreciate the help. Thanks

1 Answers

You should try using split to cut string into 2 arrays from "=" sign. Then take the second array [1] :

def version_value = sh(returnStdout: true, script: "cat build.gradle | grep -o 'version = [^,]*'").trim()
sh "echo Project in version value: $version_value"
def version = version_value.split(/=/)[1]
sh "echo final version: $version"
Related