user312307
user312307

Reputation: 140

Accessing groovy variable in shell execution step in jenkinsfile

In my Jenkinsfile, I have defined a groovy variable and I want to use that value in the below shell command:

ret is the variable which has the version value as 7.0.1.0.284 from command 1 shell execution

command1 = """curl -s "https://abc/maven-metadata.xml" | grep "<version>.*</version>" | sort | uniq | sed -e "s#\\(.*\\)\\(<version>\\)\\(.*\\)\\(</version>\\)\\(.*\\)#\\3#g"| grep 7.0.1.0 | tail -n1"""
ret = sh(script: command1 , returnStdout: true)
command2 = "wget --quiet --no-check-certificate --no-proxy https://abc-nexus.com/nexus/content/repositories/item/\$ret/item-portal-rpm-\$ret-idp-portal.rpm -P /var/jenkins/workspace/abc/item/RPMBUILD/RPMS"

Output with this command:

wget --quiet --no-check-certificate --no-proxy https://abc-nexus.com/nexus/content/repositories/item//item-portal-rpm--idp-portal.rpm -P /var/jenkins/workspace/abc/item/RPMBUILD/RPMS

It is blank and if I use it this way:

command2 = "wget --quiet --no-check-certificate --no-proxy https://abc-nexus.com/nexus/content/repositories/item/$ret/item-portal-rpm-$ret-idp-portal.rpm -P /var/jenkins/workspace/abc/item/RPMBUILD/RPMS"

Output is:

wget --quiet --no-check-certificate --no-proxy https://abc-nexus.com/nexus/content/repositories/item/7.0.1.0.284
+item-portal-rpm-7.0.1.0.284

It goes into the next line and is not considered as a single line execution.

Upvotes: 1

Views: 389

Answers (1)

Matthew Schuchard
Matthew Schuchard

Reputation: 28774

Your first attempt is escaping the $ with a \. This is interpreted in the shell interpreter as a shell variable, because it is passed to the Jenkins Pipeline sh method that way. Your second attempt is closer to correct syntax, but is safer with brackets:

command2 = "wget --quiet --no-check-certificate --no-proxy https://abc-nexus.com/nexus/content/repositories/item/${ret}/item-portal-rpm-${ret}-idp-portal.rpm -P /var/jenkins/workspace/abc/item/RPMBUILD/RPMS"

The reason you have a newline in your evaluated second command is because the stdout return from the shell interpreter for the first command has a newline delimiter at the end of it. You need to remove this newline with the trim method like so:

ret = sh(script: command1 , returnStdout: true).trim()

That will get you the result you desire.

Upvotes: 1

Related Questions