如何在Jenkinsfile中向调用的Shell脚本传递参数并用于Git提交消息?
如何在Jenkinsfile中向调用的Shell脚本传递参数并用于Git提交消息?
没问题,这完全可以实现,咱们分两步修改就能搞定:
第一步:修改Jenkinsfile,把参数传递给Shell脚本
你只需要在调用pushreqs.sh时,把some_argument作为命令行参数传过去就行。要注意如果参数里可能包含空格或者特殊字符,一定要用双引号把参数括起来,避免解析出错。修改后的requirementsPusher函数如下:
def requirementsPusher(some_argument) { sshagent(credentials: ['jenkins-key-new']){ // 将some_argument作为参数传递给shell脚本,用引号包裹避免特殊字符问题 sh("./build-scripts/pushreqs.sh \"${some_argument}\"") } }
第二步:修改pushreqs.sh脚本,接收参数并写入Git提交消息
在Shell脚本里,命令行参数可以通过$1、$2这类变量获取,这里我们的Jira工单号是第一个参数,所以用$1接收,之后把它插入到git commit的消息中即可。修改后的脚本片段如下:
#!/bin/bash set -x # echo on . ${0%/*}/common.sh # 接收Jenkins传递过来的Jira工单参数 jira_ticket="$1" staged=$(git diff --name-only --staged) if [ "$staged" == "" ] ; then echo "No changes staged, nothing to do" exit 0 elif [ "$staged" == "requirements.txt" ] ; then echo committing and pushing requirements.txt .. should be only on master and not on rebuild # 在提交消息里加入Jira工单号 git commit --no-verify -m "Version updates by Jenkins master build [${jira_ticket}]" requirements.txt || exit 3 git push origin HEAD:build_test_latest || exit 2 exit 0 else echo "Fail - unexpected changes staged: ${staged}" exit 5 fi
如果担心参数为空的情况,还可以在脚本开头加个简单的校验,比如:
if [ -z "$jira_ticket" ]; then echo "Error: No Jira ticket argument provided" exit 1 fi
这样就能确保只有传入有效参数时才会继续执行,避免提交消息里出现空括号的情况。
备注:内容来源于stack exchange,提问作者user21641220
相关产品推荐
相关产品推荐

