首页 > 解决方案 > 如何将 Shell 变量值访问到 Groovy 管道脚本中

问题描述

现在我是 Shell、Jenkins、Groovy 管道的新手。我的要求是我正在将文件文本读入 shell 脚本下的变量中,并且我需要将此变量值从 shell 脚本中传递出来并在 Groovy 脚本中使用。

这是我的代码:

stages
    {
        stage('example')
        
        {
            steps
            {
                script
                {
                    
                sh'''
                    #!/bin/bash
                    set +x                  
                    readVal=$(<$WORKSPACE/test.json)
                    echo "$readVal"        //this is priting my entire json successfully                  
                    
                  echo 'closing shell script'
                    
                ''' 
                    
                    
                    println WORKSPACE    /// this is printing my workspace value successfully 
                    
                    println readVal     // not working 
                    println env.readVal     // not working 
                    println $readVal     // not working 

                
                }
            }
        }
    }

如何readVal从 shell 中获取 ' 值以进行访问?

标签: bashshelljenkinsgroovyjenkins-pipeline

解决方案


请参阅Jenkins,管道最佳实践

一种。解决方案:不要使用[复杂函数],而是使用 shell 步骤并返回标准输出。这个外壳看起来像这样:

def JsonReturn = sh label: '', returnStdout: true, script: 'echo "$LOCAL_FILE"| jq "$PARSING_QUERY"'

例子

pipeline {
    agent any

    stages {
        stage('example') {
            steps {
                script {
                    def readVal = sh script: 'echo "READ_VAL_VALUE"', returnStdout: true
                    echo readVal
                    println readVal
                }
            }
        }
    }
}

控制台输出

[Pipeline] Start of Pipeline
[Pipeline] node
Running on Jenkins in C:\Users\jenkins\AppData\Local\Jenkins\.jenkins\workspace\Pipeline project
[Pipeline] {
[Pipeline] stage
[Pipeline] { (example)
[Pipeline] script
[Pipeline] {
[Pipeline] sh
+ echo READ_VAL_VALUE
[Pipeline] echo
READ_VAL_VALUE

[Pipeline] echo
READ_VAL_VALUE

[Pipeline] }
[Pipeline] // script
[Pipeline] }
[Pipeline] // stage
[Pipeline] }
[Pipeline] // node
[Pipeline] End of Pipeline
Finished: SUCCESS

推荐阅读