user6496685
user6496685

Reputation:

groovy escape double quoted $

I have this shell script running in a Jenkins pipeline

def planResults = sh(returnStdout: true, script: "cd $it; PLAN=\$(terragrunt plan --terragrunt-source-update | landscape); echo "$PLAN"; CHANGES=$(echo "$PLAN" | tail -2); echo $CHANGES")

The issue is when I try to echo the "$PLAN" variables.

Here is the solution that groovy recommends, which works near where PLAN is set at \$(terragrunt, however it does not work for a $ inside double quotes. And I NEED double quotes for this command to work properly.

solution: either escape a literal dollar sign "\$5" or bracket the value 
expression "${5}" @ line 34, column 148.
ce-update | landscape); echo "$PLAN"; CH

Thank you!

Upvotes: 9

Views: 26607

Answers (1)

yong
yong

Reputation: 13712

For double quoted string, Groovy will do interpolation on the string firstly.

Because the it, PLAN and CHANGES are runtime variables of the shell, rather than the variables of Groovy runtime. Groovy can't find the responding value from Groovy variable stack to replace the $it/PLAN/CHANGS during interpolation.

So you need to escape all $ if you use double quote in your case:

script: "cd \$it; PLAN=\$(terragrunt plan --terragrunt-source-update | landscape); 
         echo \$PLAN; CHANGES=\$(echo \$PLAN | tail -2); echo \$CHANGES"

Or use single quote which not support interpolation:

script: 'cd $it; PLAN=$(terragrunt plan --terragrunt-source-update | landscape); 
             echo $PLAN; CHANGES=$(echo $PLAN | tail -2); echo $CHANGES'

More detail about Groovy string at here

Upvotes: 18

Related Questions