adding quotes around shellscript parameter from Je

2019-06-05 11:09发布

问题:

I'm building a pipeline in Jenkins, and in this pipeline, I call a shellscript: sh "helm upgrade --install $app --set myVar=$myVar"

now, after trying this in the terminal on my local machine, I've discovered that for some values of myVar, it needs to be quoted on the commandline. (specifically I'm passing a YAML list, example: "{foo,bar,baz}" )

Now it turns out this is not as simple as it would seem. my first attempt was:

sh "helm upgrade --install $app --set myVar='$myVar'"

but in the logs, we see that the command that was ultimately ran looks like

sh helm upgrade --install appname --set myvar={foo,bar,baz}

and this, frustratingly, doesn't get parsed the right way by helm.

so I think to myself, "double quotes would work too", and I try:

sh "helm upgrade --install appname --set myvar=\"$myVar\""

but alas, the logs tell that same old story:

sh helm upgrade --install appname --set myvar={foo,bar,baz}

so. How do i convince my jenkins-pipeline to run the command as

sh "helm upgrade --install appname --set myvar="{foo,bar,baz}"

and also, why doesn't this work as expected?

回答1:

I have run into similar issue some time ago and the solution to this problem is quite simple, yet pretty counter intuitive. You have to escape double quote with triple backslash. Take a look at this very simple example:

node {
    stage('Test') {
        sh "echo \\\"Lorem ipsum dolor sit amet\\\""
    }
}

And this is the console output:

[Pipeline] node
Running on Jenkins in /var/jenkins_home/workspace/test-pipeline
[Pipeline] {
[Pipeline] stage
[Pipeline] { (Test)
[Pipeline] sh
[test-pipeline] Running shell script
+ echo "Lorem ipsum dolor sit amet"
"Lorem ipsum dolor sit amet"
[Pipeline] }
[Pipeline] // stage
[Pipeline] }
[Pipeline] // node
[Pipeline] End of Pipeline
Finished: SUCCESS