Score:0

Not able to use for loop using bash in Jenkins pipeline

pe flag

Following is my code

     stage ('Connect to cluster (update kubeconfig)') {
        steps {
            script {
                dir("${env.WORKSPACE}/gke-infra-creation") {
                def jsonObj;
                jsonObj = readJSON file: 'parameters.json'

                sh "gcloud container clusters get-credentials ${jsonObj.cluster_name} --zone ${jsonObj.zone} --project ${jsonObj.project}"
            
                sh "for \i in ${jsonObj.ns}; do kubectl create namespace $i}; done"
           
                sh "kubectl get nodes"
                
                }                
            }
        }
    }

It is failing with below error

  org.codehaus.groovy.control.MultipleCompilationErrorsException: startup failed:
  WorkflowScript: 53: unexpected char: '\' @ line 53, column 29.
                   sh "for \i in ${jsonObj.ns}; do kubectl create namespace $i}; done"
                           ^

  1 error

  at org.codehaus.groovy.control.ErrorCollector.failIfErrors(ErrorCollector.java:309)

If I try with $i, then it fails with below error

 hudson.remoting.ProxyException: groovy.lang.MissingPropertyException: No such property: i for class: WorkflowScript

Any suggestions to resolve this issue.

cn flag
try with double backslash `for \\i `
Score:1
jp flag
  • The first i doesn't have any special characters, so doesn't need to be escaped at all.
  • The correct way to escape a literal $ is \$.
  • You have an extraneous bracket after $i.

Try:

sh "for i in ${jsonObj.ns}; do kubectl create namespace \$i; done"
mangohost

Post an answer

Most people don’t grasp that asking a lot of questions unlocks learning and improves interpersonal bonding. In Alison’s studies, for example, though people could accurately recall how many questions had been asked in their conversations, they didn’t intuit the link between questions and liking. Across four studies, in which participants were engaged in conversations themselves or read transcripts of others’ conversations, people tended not to realize that question asking would influence—or had influenced—the level of amity between the conversationalists.