Access a Groovy variable from within shell step in Jenkins pipeline

Solution 1:

To use a templatable string, where variables are substituted into a string, use double quotes.

sh "echo $some_var"

Solution 2:

I am adding the comment from @Pedro as an answer because I think it is important.

For sh env vars we must use

sh "echo \$some_var" 

Solution 3:

You need to do something like below if a bash script is required :

Set this variable at global or local(function) level where from these can be accessible to sh script:

def stageOneWorkSpace = "/path/test1"
def stageTwoWorkSpace = "/path/test2"

In shell script call them like below

sh '''
echo ''' +stageOneWorkSpace+ '''
echo ''' +stageTwoWorkSpace+ '''
cp -r ''' +stageOneWorkSpace+'''/qa/folder1/* ''' +stageOneWorkSpace+'''/qa/folder2
'''

Make sure you start and end sh with three quotes like '''

Solution 4:

I would like to add another scenario to this discussion. I was using shell environment variables and groovy variables in the same script.

 format='html'
    for file in *.txt; 
        do mv  -- "\$file" "\${file%.txt}.$format";
    done

So here, What I have done is use \$ only for shell environment variables and use $ for groovy variables.