Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 474
Alex Avatar asked Apr 12 '17 18:04

Alex


People also ask

How do I assign a variable in Groovy script?

Variables in Groovy can be defined in two ways − using the native syntax for the data type or the next is by using the def keyword. For variable definitions it is mandatory to either provide a type name explicitly or to use "def" in replacement. This is required by the Groovy parser.

How do I write a shell script in Groovy?

To enter groovy shell you need to type groovysh in command line and hit enter. You can write any groovy expressions inside the groovy shell and run. Shell variables are all untyped. This behavior can be changed by activating interpreter mode.

What is Groovy sh?

The Groovy Shell, aka. groovysh is a command-line application which allows easy access to evaluate Groovy expressions, define classes and run simple experiments.


1 Answers

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"""
like image 146
Amy B Higgins Avatar answered Oct 04 '22 01:10

Amy B Higgins