[英]Bash variable escaping in a Jenkinsfile
I am trying the following: 我正在尝试以下方法:
sh '''
changelog=$(git log `git describe --tags --abbrev=0 HEAD^`..HEAD --oneline)
curl --data '{"\tag_name\": \\"v0.0.${BUILD_NUMBER}\\",\"target_commitish\": \"master\",\"name\": \\"Release v0.0.$BUILD_NUMBER\\",\"body\": \\"$changelog\\",\"draft\": false,\"prerelease\": false}' https://****/api/v3/repos/****/****/releases?access_token=$JENKINS_ACCESS_TOKEN_PSW
'''
Basically I want to include "dynamic" values for tag
, name
and body
which are taken using the Jenkins build number ( $BUILD_NUMBER
) and a bash variable containing the result of git log
( changelog
). 基本上,我想包括使用Jenkins内部版本号(
$BUILD_NUMBER
)和包含git log
结果的bash变量( changelog
)获取的tag
, name
和body
“动态”值。
I've made all sort of single and double quotes and other escaping changes that I am not sure anymore how it should be. 我已经进行了各种单引号和双引号以及其他转义的更改,这些更改我现在不确定应该如何。
This currently fails with: 当前,此操作失败并显示:
curl: (6) Could not resolve host: variable
curl:(6)无法解析主机:变量
curl: (6) Could not resolve host: escapingcurl:(6)无法解析主机:转义
curl: (6) Could not resolve host: 9a21d71curl:(6)无法解析主机:9a21d71
curl: (6) Could not resolve host: morecurl:(6)无法解析主机:更多
curl: (6) Could not resolve host: escapingcurl:(6)无法解析主机:转义
curl: (6) Could not resolve host: attemptscurl:(6)无法解析主机:尝试
curl: (6) Could not resolve host: 708ed0fcurl:(6)无法解析主机:708ed0f
curl: (6) Could not resolve host: morecurl:(6)无法解析主机:更多
curl: (6) Could not resolve host: escaping'curl:(6)无法解析主机:转义'
It can't handle the contents inside the changelog
variable. 它无法处理
changelog
变量中的内容。
The challenge here is not just to properly escape the quotes when dynamically generating a string, but also to ensure that the result is a valid JSON. 这里的挑战不仅是在动态生成字符串时正确地转义引号,而且还要确保结果是有效的JSON。 For example in your case
changelog
may contain newlines and quotes and, when it is expanded into the "body": "$changelog"
part of your POST data, those characters must be properly escaped. 例如,在您的情况下,
changelog
可能包含换行符和引号,并且在将其扩展为POST数据的"body": "$changelog"
部分时,必须正确转义那些字符。
To this end use the jq utility to generate the POST JSON data as explained in the answer to a similar question : 为此,使用jq实用程序来生成POST JSON数据,如对类似问题的回答中所述:
sh '''
changelog=$(git log `git describe --tags --abbrev=0 HEAD^`..HEAD --oneline)
jq -n --arg tagname "v0.0.$BUILD_NUMBER" \
--arg name "Release v0.0.$BUILD_NUMBER" \
--arg body "$changelog" \
'{"tag_name": $tagname, "target_commitish": "master", "name": $name, "body": $body, "draft": false, "prerelease": false}' |
curl -d@- https://****/api/v3/repos/****/****/releases?access_token=$JENKINS_ACCESS_TOKEN_PSW
'''
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.