【问题标题】:In a Jenkinsfile, how to access a variable that is declared within a sh step?在 Jenkinsfile 中,如何访问在 sh 步骤中声明的变量?
【发布时间】:2019-09-01 16:11:19
【问题描述】:

假设我有一个 Jenkinsfile。在该 Jenkinsfile 中,是以下 sh 步骤:

sh "myScript.sh"

在 myScript.sh 中,声明了以下变量:

MY_VARIABLE="This is my variable"

如何从我的 Jenkinsfile 访问在 myScript.sh 中声明的 MY_VARIABLE?

【问题讨论】:

  • 您无法访问在 Jenkinsfile 的 shell 脚本中声明的变量。其他方式是可能的,建议使用。

标签: bash variables groovy jenkins-pipeline sh


【解决方案1】:

要将脚本中定义的变量导入当前 shell,可以使用source 命令(参见explanation on SU):

# Either via command
source myScript.sh
# Or via built-in synonym
. myScript.sh

假设您的脚本不输出任何内容,您可以改为输出变量以在 Jenkins 中获取它:

def myVar = sh(returnStdout: true, script: '. myScript.sh && echo $MY_VARIABLE')

如果确实输出来自您的脚本,您可以获取每个 shell 的最后一个输出:

(. myScript.sh && echo $MY_VARIABLE) | tail -n1

或通过 Groovy:

def out = sh(returnStdout: true, script: '. myScript.sh && echo $MY_VARIABLE')
def myVar = out.tokenize('\n')[-1]

【讨论】:

    【解决方案2】:

    .sh 文件中声明的 bash 变量以管道步骤结束:sh 完成。

    但是你可以让你 .sh 生成一个属性文件,然后使用管道步骤:readProperties 将文件读入对象进行访问。

    // myScript.sh
    ...
    
    echo MY_VARIABLE=This is my variable > vars.properties
    
    
    // pipeline 
    sh 'myScript.sh'
    def props = readProperties file: 'vars.properties'
    echo props.MY_VARIABLE
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-07-28
      • 1970-01-01
      • 2012-03-16
      • 1970-01-01
      • 2012-05-05
      • 1970-01-01
      • 2015-03-31
      • 1970-01-01
      相关资源
      最近更新 更多