I am currently developing a Jenkins shared library and need to use a dynamic Groovy variable inside an sh script execution. I’ve tried several syntax variations with double and single quotes, but the shell either doesn't recognize the variable or throws a syntax error. What is the standard way to export a Groovy string so it is accessible as an environment variable in the shell environment?
3 answers
The most common way to achieve this in a Jenkins Pipeline is through double-quoted strings, which allow for Groovy interpolation. If you have a variable def myVar = 'iCertData', you can use it inside a shell block like sh "echo ${myVar}". However, if you need the variable to persist as a true environment variable for complex scripts, you should use the withEnv block or assign it to the env object, such as env.MY_SHELL_VAR = myVar. This ensures that any subsequent shell calls within that scope can access the value using standard shell syntax like $MY_SHELL_VAR. Just be careful with special characters; if your Groovy variable contains shell-sensitive symbols, you may need to escape them to prevent command injection or execution failures.
Does using double quotes for interpolation cause issues when your shell script also contains native shell variables like $PATH that you don't want Groovy to try and resolve?
For simple scripts, I just use sh "export MY_VAR=${groovyVar} && ./myscript.sh". It’s straightforward and keeps the variable scope limited to that specific execution.
I agree with Cynthia for one-off tasks. It’s a very practical "quick fix." However, as Rebecca mentioned she is working on a shared library, the env or withEnv patterns are generally preferred for reusability and to keep the pipeline logs much cleaner and easier to debug during a failure.
Kevin, that is a classic problem. If you use double quotes for the sh block to allow Groovy interpolation, you must escape your native shell variables with a backslash, like \$PATH, otherwise Groovy will look for a variable named PATH in its own context and fail. A cleaner alternative is to use the env object approach I mentioned earlier. By setting env.MYVAR = groovyVar, you can use a single-quoted shell block sh 'echo $MYVAR && echo $PATH', where the shell handles all variable resolution, keeping your Groovy and Shell logic cleanly separated.