Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to pass variables from Jenkinsfile to shell command

I want to use a variable which I am using inside of my Jenkinsfile script, and then pass its value into a shell script execution (either as an environment variable or command line parameter).

But the following Jenkinsfile:

for (i in [ 'a', 'b', 'c' ]) {     echo i     sh 'echo "from shell i=$i"' } 

Gives the output:

a from shell i= b from shell i= c from shell i= 

Desired output is something like:

a from shell i=a b from shell i=b c from shell i=c 

Any idea how to pass the value of i to the shell scipt?

Edit: Based upon Matt's answer, I now use this solution:

for (i in [ 'a', 'b', 'c' ]) {     echo i     sh "i=${i}; " + 'echo "from shell i=$i"' } 

The advantage is, that I don't need to escape the " in the shell script.

like image 701
Joe Avatar asked Jan 08 '17 23:01

Joe


People also ask

How do you pass a variable inside a shell script?

In a shell script, you can pass variables as arguments by entering arguments after the script name, for example ./script.sh arg1 arg2 . The shell automatically assigns each argument name to a variable. Arguments are set of characters between spaces added after the script.


1 Answers

Your code is using a literal string and therefore your Jenkins variable will not be interpolated inside the shell command. You need to use " to interpolate your variable inside your strings inside the sh. ' will just pass a literal string. So we need to make a few changes here.

The first is to change the ' to ":

for (i in [ 'a', 'b', 'c' ]) {   echo i   sh "echo "from shell i=$i"" } 

However, now we need to escape the " on the inside:

for (i in [ 'a', 'b', 'c' ]) {   echo i   sh "echo \"from shell i=$i\"" } 

Additionally, if a variable is being appended directly to a string like you are doing above ($i onto i=), we need to close it off with some curly braces:

for (i in [ 'a', 'b', 'c' ]) {   echo i   sh "echo \"from shell i=${i}\"" } 

That will get you the behavior you desire.

like image 126
Matt Schuchard Avatar answered Sep 21 '22 22:09

Matt Schuchard