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.
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.
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.
The Groovy Shell, aka. groovysh is a command-line application which allows easy access to evaluate Groovy expressions, define classes and run simple experiments.
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"""
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With