Jenkins pipeline I need to execute the shell command and the result is the value of def variable.
What shall I do? Thank you

def projectFlag = sh("`kubectl get deployment -n ${namespace}| grep ${project} | wc -l`")
    if ( "${projectFlag}" == 1 ) {
         def projectCI = sh("`kubectl get deployment ${project} -n ${namespace} -o jsonpath={..image}`")
         echo "$projectCI"
       } else if ( "$projectCI" == "${imageTag}" ) {
           sh("kubectl delete deploy ${project} -n ${namespaces}")
           def redeployFlag = '1'
            echo "$redeployFlag"
         if ( "$projectCI" != "${imageTag}" ){
          sh("kubectl set image deployment/${project} ${appName}=${imageTag} -n ${namespaces}")
      else {
        def redeployFlag = '2'

1 Answers

metalisticpain On Best Solutions

I believe you're asking how to save the result of a shell command to a variable for later use?

The way to do this is to use some optional parameters available on the shell step interface. See for the documentation

def projectFlag = sh(returnStdout: true,
    script: "`kubectl get deployment -n ${namespace}| grep ${project} | wc -l`"

Essentially set returnStdout to true. The .trim() is critical for ensuring you don't pickup a \n newline character which will ruin your evaluation logic.