passing variable to bash script in a jenkins pipeline job passing variable to bash script in a jenkins pipeline job linux linux

passing variable to bash script in a jenkins pipeline job


If you are using multiline shell script with triple apostrophe, you have to use this syntax:

sh ''' echo '''+varToPrint+''' other commands...'''

(from https://medium.com/devopslinks/a-hacky-hackers-guide-to-hacking-together-jenkins-scripted-pipelines-part-3-aca73bd33eaa)


The example below works:

void updateApplicationVersionMaven(String version) {    sh "mvn -B versions:set -DnewVersion=$version"}

And a complete pipeline script (tested on Jenkins 2.7.3):

node {    stage('test') {        def testVar='foo'        sh "echo $testVar"        }}

EDIT (after comments): Ah, tested some more and could reproduce the issue. It's because you're sourcing the script with ". /opt/setup.sh". This influences the shell environment, and in this case breaks the Jenkins variable injection. Interesting.

EDIT2 (after comments): I believe this is an issue with the default shell that's being used (either by Jenkins or by the OS).I could reproduce the issue from the comments and was able to work around it by explicitly using bash as a shell:

def testVar='foo3'sh "bash -c \". /var/jenkins_home/test.sh $testVar && echo \$ARCH\""

The last echo now echos the contents of testVar that was passed as an argument to the script and subsequently set by the script as an environment variable.


Had the same problem and the posted solutions did not work for me. Using environment variables did the trick:

env.someVar='someVal'sh "echo  ${env.someVar}"