Jenkins:如何从shell命令中存储和读取变量

fnx2tebb  于 2023-10-17  发布在  Jenkins
关注(0)|答案(1)|浏览(124)

在我的Jenkins管道中,我试图根据版本号从我的项目文件夹中创建一个zip文件。为此,我从一个toml文件中提取版本号并存储在一个变量中,但在打印该变量 (在Zip阶段) 时,它显示**"${version}"**。
我认为要么我没有正确地存储值,要么我没有正确地打印。
我的Groovy脚本是:

pipeline {
    agent any
    parameters {
        string(description: 'Enter the git branch to be built', name: 'branch', defaultValue: 'master', trim: true)
        choice(choices: 'Build\nPromote', description: 'Select the branch to build', name: 'runtype')
    }
    
    stages {
        stage('Checkout') {
            steps {
                script {
                    if ( params.branch == '') {
                        echo "Building commit with Tag: master"
                        checkout([$class: 'GitSCM', branch: '${params.branch}', extensions: [], userRemoteConfigs: [[credentialsId: 'Aiman_Sarosh_cred', url: 'https://mygit.server/myproject.git']]])
                        echo "Built at path: ${WORKSPACE}"
                        sh 'ls -l ${WORKSPACE}'
                    }
                    else {
                        echo "Building commit with Tag: ${params.branch}"
                        checkout([$class: 'GitSCM', branch: '${params.branch}', extensions: [], userRemoteConfigs: [[credentialsId: 'Aiman_Sarosh_cred', url: 'https://mygit.server/myproject.git']]])
                        echo "Built at path: ${WORKSPACE}"
                        sh 'ls -l ${WORKSPACE}'
                    }    
                }
            }
        }
        stage('Zip') {
            steps {
                script {
                    version=sh 'grep -m 1 version_number ${WORKSPACE}/ComponentInfo.toml | tr -s \' \' | tr -d \'"\' | tr -d "\'" | cut -d\' \' -f3'
                    echo 'Version: ${version}'
                }
            }
        }
    }
}

并且输出是

17:05:05  [Pipeline] stage
17:05:05  [Pipeline] { (Zip)
17:05:05  [Pipeline] script
17:05:05  [Pipeline] {
17:05:06  [Pipeline] sh
17:05:07  + grep -m 1 version_number /apps/external/5/jenkins-node-home/workspace/APPL004316/APIN004621/myproject/ComponentInfo.toml
17:05:07  + tr -s ' '
17:05:07  + tr -d '"'
17:05:07  + tr -d ''\'''
17:05:07  + cut '-d ' -f3
17:05:07  0.1.29
17:05:07  [Pipeline] echo
17:05:07  Version: ${version}
17:05:07  [Pipeline] }
17:05:07  [Pipeline] // script
17:05:07  [Pipeline] }
17:05:07  [Pipeline] // stage
17:05:07  [Pipeline] }
17:05:07  [Pipeline] // node
17:05:07  [Pipeline] End of Pipeline
17:05:07  Finished: SUCCESS
erhoui1w

erhoui1w1#

sh步骤默认不返回命令输出,需要用returnStdout: true参数调用。由于你将使用多个参数,你需要给它们命名:

def version = sh script: 'your command’, returnStdout: true

相关问题