Alex
Alex

Reputation: 2805

groovy script - sh with variable

Missing something obvious. How do I pass a variable from a groovy script into a shell command? This is in the context of a Jenkinsfile if it matters for syntax.

def COLOR

node('nodename'){

    stage ('color') {

        COLOR = "green"
        echo "color is $COLOR"

        sh '''COLOR=${COLOR}
        echo $COLOR'''

    }
}

I expect to see the shell bit print green, but I'm getting the following;

[Pipeline] echo
color is green
[Pipeline] sh
[job] Running shell script
+ COLOR=
+ echo

I have to use triple quoting on the sh because of the content that's going to go in there once I get this straightened out.

Upvotes: 11

Views: 74871

Answers (3)

Raj Polakala
Raj Polakala

Reputation: 1

COLOR = "green"

sh label: '', script: "echo $COLOR"

Upvotes: 0

Amy B Higgins
Amy B Higgins

Reputation: 71

If the code here is meant to assign the groovy variable value ("green") to the environment variable COLOR, and echo $COLOR is meant to print out the shell variable, the $ needs to be escaped like so that the shell can read it, like this:

sh """COLOR=${COLOR}
echo \$COLOR"""

Upvotes: 4

M A
M A

Reputation: 72884

You have to use double quotes instead of single in order to replace expressions in the string:

def COLOR

node('nodename'){

    stage ('color') {

        COLOR = "green"
        echo "color is $COLOR"

        sh """COLOR=${COLOR}
        echo $COLOR"""

    }
}

If single quotes need to be used for some reason, try concatenating using +:

sh '''COLOR=''' + COLOR + '''
    echo ''' + COLOR

Upvotes: 22

Related Questions