首页 > 解决方案 > 从 jenkinsfile 执行 shell 命令

问题描述

我正在尝试从 jenkinsfile 执行一组命令。问题是,当我尝试将 stdout 的值分配给一个变量时,它不起作用。我尝试了双引号和单引号的不同组合,但到目前为止没有运气。

在这里,我使用最新版本的 jenkinsfile 以及旧版本执行了脚本。将 shell 命令放入 """ """ 中不允许创建新变量并给出诸如 client_name 命令不存在之类的错误。

String nodeLabel = env.PrimaryNode ? env.PrimaryNode : "slave1"
echo "Running on node [${nodeLabel}]"

node("${nodeLabel}"){

    sh "p4 print -q -o config.yml //c/test/gradle/hk/config.yml"
    def config = readYaml file: 'devops-config.yml'
    def out = sh (script:"client_name=${config.BasicVars.p4_client}; " +
    'echo "client name: $client_name"' +
    " cmd_output = p4 clients -e $client_name" +
    ' echo "out variable: $cmd_output"',returnStdout: true)
}

我想将命令 p4 clients -e $client_name 的标准输出分配给变量 cmd_output。

但是当我执行代码时,抛出的错误是:

NoSuchPropertyException:client_name 未在 cmd_output = p4 clients -e $client_name 行定义

我在这里想念什么?

标签: jenkins-pipelinedsljenkins-groovy

解决方案


您的问题是,当字符串用双引号引起来时,詹金斯会解释所有 $ 。所以前两次没有问题,因为第一个变量来自詹金斯,第二次是单引号字符串。第三个变量在双引号字符串中,因此 jenkins 尝试用它的值替换该变量,但它找不到它,因为它仅在执行 shell 脚本时生成。

解决方案是转义 $client_name 中的 $(或在环境块中定义 client_name)。

我重写了块:

String nodeLabel = env.PrimaryNode ? env.PrimaryNode : "slave1"
echo "Running on node [${nodeLabel}]"

node("${nodeLabel}"){
    sh "p4 print -q -o config.yml //c/test/gradle/hk/config.yml"
    def config = readYaml file: 'devops-config.yml'
    def out = sh (script: """
        client_name=${config.BasicVars.p4_client}
        echo "client name: \$client_name"
        cmd_output = p4 clients -e \$client_name
        echo "out variable: \$cmd_output"
    """, returnStdout: true)
}

推荐阅读