首页 > 解决方案 > 如何通过 Jenkinsfile 在批处理中使用变量执行 Git 命令

问题描述

我有以下 Jenkinsfile 内容,可以根据需要创建标签名称并存储在变量“标签”中。如何在批处理命令中使用该变量?

请注意,Jenkins 在 Windows 机器上,因此使用 bat 命令。如果有一种简单的方法可以切换到 bash,我会全力以赴。但主要问题如下。谢谢你。

如何使用该“标签”变量(在我尝试在批处理命令中使用它之前存储了正确的值)?目前它没有任何价值,我在下面的实现试图回应它。

#!/usr/bin/groovy

pipeline{
    agent any
    stages {
        stage('tag stage'){
            steps {
                gitTag()
            }
        }
    }
}

def gitTag(){
    String date = new Date().format('yyyyMMddhhmmss')
    String branch = "${env.GIT_BRANCH}"
    String tag = "v${date}-${branch}"
    tag = tag.replaceAll('/', '-')
    String message = "tagged via jenkins - ${tag}"
    print message

    bat 'echo Hello test'
    bat 'echo from bat before tag %tag% after tag'
    bat 'git tag -a %tag% -m "tagging with %message%"'
    bat 'git push origin %tag%'
}

标签: batch-filejenkinsgroovy

解决方案


似乎由于单引号,groovy 无法插入变量。另外,使用${var}格式。以下应该可以解决问题:

def gitTag(){
    String date = new Date().format('yyyyMMddhhmmss')
    String branch = "${env.GIT_BRANCH}"
    String tag = "v${date}-${branch}"
    tag = tag.replaceAll('/', '-')
    String message = "tagged via jenkins - ${tag}"
    print message

    bat "echo from bat before tag ${tag} after tag"
    bat "git tag -a ${tag} -m \"tagging with ${message}\""
    bat "git push origin ${tag}"
}

推荐阅读