如何在Shell脚本中访问循环的jenkins groovy变量的值

时间:2019-10-30 07:45:18

标签: linux shell jenkins-groovy

当我传递在jenkins Groovy脚本中声明的变量的值时,其值未保留在远程服务器上运行的for循环中。奇怪的是,我能够在for循环外访问相同的值。

这是我要使用的示例代码

#!/usr/bin/env groovy

def config
def COMMANDS_TO_CHECK='curl grep hello awk tr mkdir bc'
pipeline {

    agent {
        label "master"
    }

    stages {
            stage ('Validation of commands') {         
            steps {
                script {
                    sh """
                    #!/bin/bash
                    /usr/bin/sshpass -p passwrd ssh user@host << EOF
                    hostname

                      echo $COMMANDS_TO_CHECK ---> This is printed
                          for CURRENT_COMMAND in \$COMMANDS_TO_CHECK
                        do
                        echo ${CURRENT_COMMAND}  ---> Why This is not printed?
                        echo \${CURRENT_COMMAND} ----> Why This is not printed?
                        done
                        hostname
EOF
                        exit

"""

}
}
}
}
}

输出

[workspace@3] Running shell script
+ /usr/bin/sshpass -p passwrd ssh user@host
Pseudo-terminal will not be allocated because stdin is not a terminal.
illinsduck01
curl grep hello awk tr mkdir bc
illinsduck01
+ exit

1 个答案:

答案 0 :(得分:0)

您可以如下所示将sh包裹在““” ...“”“中

#!/usr/bin/env groovy

def config
pipeline {
agent {
    label "master"
}
stages {
    stage ('Validation of commands') {         
        steps {
            script {
            sh """#!/bin/sh
            /usr/bin/sshpass -p password ssh username@hostname << EOF
            COMMANDS_TO_CHECK="curl grep hello awk tr mkdir bc"


            hostname

            echo \$COMMANDS_TO_CHECK

            for CURRENT_COMMAND in \$COMMANDS_TO_CHECK
            do
            echo \$CURRENT_COMMAND
            which \$CURRENT_COMMAND
            status=\$?

            if [ \${status} -eq 0 ]
            then
               echo  \${CURRENT_COMMAND} command is OK
            else
               echo "Failed to find the \${CURRENT_COMMAND} command"
            fi
            done
            hostname
            EOF

            exit    
           """
           }
         }
       }
     }
  }