开发者社区> 问答> 正文

如何在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

"""

}
}
}
}
}

输出量

展开
收起
祖安文状元 2020-01-08 15:31:29 1622 0
1 条回答
写回答
取消 提交回答
  • 您可以将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    
               """
               }
             }
           }
         }
      }
    
    2020-01-08 15:31:37
    赞同 展开评论 打赏
问答排行榜
最热
最新

相关电子书

更多
Shell 脚本速查手册 立即下载
Alibaba Cloud CodePipeline 基于Jenkins的CI / CD探索之路 立即下载
低代码开发师(初级)实战教程 立即下载