How to pass variables from a Jenkinsfile to a shell command

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

But the following Jenkinsfile :

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

Gives output:

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

The desired output looks something like this:

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

Any idea how to pass i value to scipt shell?

Edit: Based on 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 do not need to hide " in the shell script.

+6
source share
3 answers

Your code uses a literal string, so your Jenkins variable will not be interpolated inside the shell command. You need to use " to interpolate the variable inside the lines inside sh . ' Just pass the literal string. Therefore, we need to make a few changes.

First, you need to change the ' to " :

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

However, now we need to avoid the " inside:

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

In addition, if the variable is added directly to the line, as you do above ( $i by i= ), we need to close it with some curly braces:

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

This will give you the behavior you desire.

+8
source

Extending to Matts: For scenarios with multiple sh lines, use

 sh """ echo ${paramName} """ 

instead

 sh '''...''' 
+3
source

try the following:

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

Source: https://habr.com/ru/post/1013893/


All Articles