Jenkins pipeline script - How to use variable as a variable name


I have a groovy script as my Jenkins pipeline script, which looks something like

node(“nodeName”) {

. . . (some groovy code)

sh “”"

< This section of the shell script calculates the value of the variable varName, example being BUILD_NUMBER >

echo “${env.BUILD_ID}” # This prints expected output. Example : 51

export varName=“env.BUILD_NUMBER”

echo “${”$varName"}" # This prints the output as env.BUILD_NUMBER and not 51



In the above example, I had hard coded value of varName as env.BUILD_NUMBER. In my actual script, value of varName will be calculated during execution.

In bash script, this result can be achieved as follows:



echo “${!variable_2}”

Exclamation mark (!) doesn’t work in shell script inside Jenkins pipeline

Can someone please explain, how to address my requirement ?

Thank you


In a shell script, you would want to use export

export varName="BUILD_NUMBER"

The env. portion is just useful inside of the groovy part of the pipeline. Everything in env is exported as an actual environment variable in the shell script.


Agree that everything in env is exported to actual environment variables in the shell script

However env. does print expected output

As I had mentioned in my original post echo “${env.BUILD_ID}” # This prints expected output. Example : 51


export varName=BUILD_NUMBER

echo “${”$varName"}"

prints the output as BUILD_NUMBER and not acuatl build number

Thank you

is that a shell echo or a pipeline echo?

for pipeline, based on jenkins - Jenkinsfile Declarative Pipeline defining dynamic env vars - Stack Overflow it looks like you can do env."$varName" but to me this seems like a code smell, and dangerously close to eval.

If your shell script is wrapped in double quotes, then ${env.BUILD_ID} is being replaced by groovy and not the shell. Can you share your pipeline (redacted)? It would help understand your context better.