Jenkins 脚本管道:无法在 shell 中打印变量并在 shell 中设置变量值 [英] Jenkins scripted pipeline: Unable to print variables inside shell and set variable values in shell
问题描述
Jenkins 脚本化管道.两个问题:
Jenkins scripted pipeline. Two issues:
- 我有一个全局变量 var,我想在里面访问它的值壳.但它什么也不打印
- 我在其中一个阶段中使用 a 设置的 var 值shell-script,在下一阶段访问,但它在 shell 中不打印任何内容.
我错过了什么?(见下面的脚本)
What am i missing? (See script below)
node {
var=10
stage('HelloWorld') {
sh '''
echo "Hello World. Var=$var" ===> Prints nothing for var
var=20'''
}
stage('git clone') {
echo "Cloning git. Var = $var" ==> Prints 20, and not 10
sh '''
echo "Var in second stage is = $var" ===> Doesnt print anything here. I need 20.
'''
}
}
推荐答案
1.将 groovy 变量传递给 shell
您的示例不起作用,因为您使用的是带单引号的字符串文字.来自 Groovy 手册(重点是我的):
任何 Groovy 表达式都可以插入到所有字符串文字中,除了单和三重单引号字符串.
Any Groovy expression can be interpolated in all string literals, apart from single and triple-single-quoted strings.
试试这个:
sh "echo 'Hello World. Var=$var'"
或者这个:
sh """
echo 'Hello World. Var=$var'
echo 'More stuff'
"""
2.从 shell 设置 Groovy 变量
您不能从 shell 步骤直接设置 Groovy 变量.这仅适用于从 Groovy 到 shell 的一个方向.相反,您可以设置退出代码或将数据写入 Groovy 可以读取的标准输出.
2. Set a Groovy variable from shell
You can't directly set a Groovy variable from a shell step. This only works in one direction from Groovy to shell. Instead you can set an exit code or write data to stdout which Groovy can read.
为参数 returnStatus
传递 true
并从 shell 脚本设置退出代码,该代码将作为 sh
步骤的返回值.
Pass true
for parameter returnStatus
and set an exit code from the shell script which will be the return value of the sh
step.
var = sh script: 'exit 42', returnStatus: true
echo "$var" // prints 42
返回单个字符串
为参数returnStdout
传递true
,并使用shell脚本中的echo
输出字符串数据.
Return a single string
Pass true
for parameter returnStdout
and use echo
from shell script to output string data.
var = sh script: "echo 'the answer is 42'", returnStdout: true
echo "$var" // prints "the answer is 42"
返回结构化数据
为参数returnStdout
传递true
,并使用shell脚本中的echo
以JSON格式输出字符串数据.
Return structured data
Pass true
for parameter returnStdout
and use echo
from shell script to output string data in JSON format.
使用 解析 Groovy 代码中的 JSON 数据JsonSlurper
.现在您有了一个可以查询的常规 Groovy 对象.
Parse JSON data in Groovy code using JsonSlurper
. Now you have a regular Groovy object that you can query.
def jsonStr = sh returnStdout: true, script: """
echo '{
"answer": 42,
"question": "what is 6 times 7"
}'
"""
def jsonData = new groovy.json.JsonSlurper().parseText( jsonStr )
echo "answer: $jsonData.answer"
echo "question: $jsonData.question"
这篇关于Jenkins 脚本管道:无法在 shell 中打印变量并在 shell 中设置变量值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!