Jenkins Pipeline String and for-Loop

I'm creating a jenkins pipeline which has a string as a variable of 1 or more items

text="test1.var1.eu-20190414121923517200000001 test2.var2.ue1-20190414121925623400000002 test3.var3.ue1-20190414121926583500000003"

I basically want to go in a loop and for each item run an action. for example echo each one in turn. The echo would look at the string and return each item in a for loop where there are 1 or more results

expected result:

test1.var1.eu-20190414121923517200000001

test2.var2.ue1-20190414121925623400000002

test3.var3.ue1-20190414121926583500000003

I've tried a few things including adding a sh to run a for loop

#!/usr/local/bin/groovy

pipeline {
  parameters {
    choice(choices: "1\n2\n3", description: 'The length of time for the environment to remain up', name: 'hours')
  }

  stages {
    stage('get and update hours') {
      steps {
        script {
          env.text="test1.var1.eu-20190414121923517200000001 test2.var2.ue1-20190414121925623400000002 test3.var3.ue1-20190414121926583500000003"
          sh "echo ${text}"
          sh "for value in ${text}; do echo $value; done"
        }
      }
    }
  }
}

expected result

test1.var1.eu-20190414121923517200000001

test2.var2.ue1-20190414121925623400000002

test3.var3.ue1-20190414121926583500000003

actual result:

[Pipeline] End of Pipeline [Office365connector] No webhooks to notify groovy.lang.MissingPropertyException: No such property: value for class: > groovy.lang.Binding at groovy.lang.Binding.getVariable(Binding.java:63) at org.jenkinsci.plugins.scriptsecurity.sandbox.groovy.SandboxInterceptor.onGetProperty(SandboxInterceptor.java:264) at org.kohsuke.groovy.sandbox.impl.Checker$6.call(Checker.java:288) at org.kohsuke.groovy.sandbox.impl.Checker.checkedGetProperty(Checker.java:292) at org.kohsuke.groovy.sandbox.impl.Checker.checkedGetProperty(Checker.java:268)

4

1 Answer

At which point you want to split this into particular texts? In general this part is missing .split(' ').

def texts = text.split(' ')
for (txt in texts) {
    sh "echo ${txt}"
}

If you really want to do that in your shell directly add escaped quotes and use a variable

sh "test=\"${text}\";for value in $test; do echo $value; done"
4

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Alexander Ross

Alexander Ross

Gaming, Esports & Interactive Media Writer

Alexander Ross has covered the video game industry for a decade, writing deep dives on game design, esports tournaments, VR developments, and gaming culture.

Share this article
Twitter Facebook Pinterest