jenkins-pipeline - 从 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 尝试用它的值替换该变量,但它找不到它,因为它仅在执行 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)
}
推荐阅读
- linux - bash 循环遍历没有扩展名的文件
- linux - 让一个程序通过 ssh 执行另一个程序
- python - tensorflow 增强树分类器多类
- excel - VBA Excel 代码 - Windows 弹出窗口打开或保存
- ios - 如何使用 swift 和 Xcode 开发 iOS 应用程序来读取和写入同一个文件
- python - 如何在 Python 中正确定义函数?
- linq - 林克。选择包含任何数组字符
- javascript - 根据其他列表选定值更新下拉列表中的选定值
- python - 从列表中随机选择的值的最近邻居?
- amazon-web-services - 将用户名发送到通过 AWS Cognito 注册用户时触发的 AWS Lambda 函数