The power that the bash shell affords is hard describe and its familiarity makes the bash shell my go to for almost everything. But I’m continuing on the process of JP (Jenkins Pipelines).

With that end, I need to have some variables defined at the beginning of the run and used throughout the entire job. Sometimes these variables will be defined in Groovy.

Example 1

Lang: groovy
def var1 = 'hello world'
node('master'){
  stage('HW1'){
    echo var1
  }
}

output:

Lang:
hello world

And sometimes it makes more sense to use bash to create the variable; trim is desired to remove the newline created by echo.

Example 2

Lang: groovy
node('master'){
  def var2 = sh (returnStdout: true, script: "echo \'hello world\'").trim()
  stage('HW2'){
    sh "echo '${var2} \${SHELL}'"
  }
}

output:

Lang:
[in_jenkins-dsl-test_hw_test-L6OPGZSILNYU4LFJKDMY4AGUBMSB2FT3Z3UAW66ODUIPZN4WUNBA] Running shell script
+ echo 'hello world ${SHELL}'
hello world ${SHELL}

Example 2 does have a couple special things. For one using the double quotes when calling shell allows for Groovy interpolation. Two using the single quotes in the shell does not allow for shell interpolation, but since it is a Groovy variable it substituted.

To allow shell interpolation

Example 3

Lang: groovy
node('master'){
  def var3 = sh (returnStdout: true, script: "echo \'hello world\'").trim()
  stage('HW3'){
    sh "echo \"${var3} \${SHELL}\""
  }
}

output:

Lang:
[in_jenkins-dsl-test_hw_test-L6OPGZSILNYU4LFJKDMY4AGUBMSB2FT3Z3UAW66ODUIPZN4WUNBA] Running shell script
+ echo 'hello world /sbin/nologin'
hello world /sbin/nologin