Bikram Agarwal
Bikram Agarwal

Reputation: 53

How to declare a new variable inside a shell block in groovy script?

For the life of me, I can't figure out how to declare and use new variables inside a shell block in a groovy script.

For example, this shell block -

sh """
    export earlist='abc.ear,def.ear'
    echo $earlist;
"""

throws an error saying

No such property: earlist for class: GroovyUserScript

If I add a def earlist before the sh, then it throws error saying -

No signature of method: GroovyUserScript.sh() is applicable for argument types: (org.codehaus.groovy.runtime.GStringImpl) values: [ export earlist='abc.ear,def.ear' echo ;

Can someone please help me with how to declare and then use variable inside a shell block, in a groovy script?

Upvotes: 1

Views: 3393

Answers (2)

Bikram Agarwal
Bikram Agarwal

Reputation: 53

After consulting with senior experts at my workplace, I found the solution I was looking for.

The problem with this code -

sh """
    export earlist='abc.ear,def.ear'
    echo $earlist;
"""

is that when I say $earlist, the compiler looks for a groovy variable named earlist and doesn't find it. Since earlist there is a shell variable, I need to escape the $. So, the correct code is -

sh """
    earlist='abc.ear,def.ear'
    echo \$earlist;
"""

Bonus TIL - if I access a groovy variable inside a shell block, the access is Read-Only. I can't edit the value of the groovy variable, even temporarily within the shell block. If I do want to do that, I can assign the groovy variable to a shell variable, manipulate the shell variable value, save the modified value in a file and when the shell block ends, read the file into the original groovy variable.

Upvotes: 2

t0r0X
t0r0X

Reputation: 4772

Use a triple single quoted string instead, which doesn't interpolate variables:

sh '''
    export earlist='abc.ear,def.ear'
    echo $earlist;
'''

See here the documentation on triple single quoted strings: http://groovy-lang.org/syntax.html#_triple_single_quoted_string

Here a overview of the available string types in Groovy: http://groovy-lang.org/syntax.html#_string_summary_table

Upvotes: 0

Related Questions