Jenkins脚本化管道:无法在Shell中打印变量并在Shell中设置变量值

问题描述 投票:0回答:2

Jenkins脚本化管道。两个问题:

  1. 我有一个全局变量var,我正在尝试访问其值贝壳。但它什么也没打印
  2. var的值,我在其中一个阶段使用ashell脚本,可在下一阶段访问,但在shell中不打印任何内容。

我想念的是什么? (请参见下面的脚本)

node {    
    var=10
    stage('HelloWorld') {
        sh '''
              echo "Hello World. Var=$var"  ===> Prints nothing for var
              var=20'''

    }
    stage('git clone') {
        echo "Cloning git. Var = $var"  ==> Prints 20, and not 10
        sh '''
          echo "Var in second stage is = $var"   ===> Doesnt print anything here. I need 20.
        '''
    }
}
jenkins
2个回答
0
投票

使用withEnv,我们可以定义&然后访问全局变量,如果您使用声明性管道,则可以在阶段级别进行访问。对于脚本式脚本,我们可以按照以下方式使用临时文件在各个阶段之间进行访问,以产生所需的输出。

node {    
    withEnv(['var=10']){
    stage('HelloWorld') {
        sh '''
              echo "Hello World. Var=$var" # This will print 10 from Global scope declared & defined with withEnv
              var=20
              # Hold that value in a file
              echo 20 > ${WORKSPACE}/some.file 
        '''

    }
    stage('git clone') {
        echo "Cloning git. Var = $var"  // This will print 10 as well!
        sh '''
          v=$(<${WORKSPACE}/some.file)
          echo "Var in second stage is = $v"   # Get variable value from prior stage
          rm -f ${WORKSPACE}/some.file
        '''
    }

    }
}

0
投票
  1. 这不起作用,因为您正在使用带单引号的字符串文字。从Groovy manual(强调我的):

    任何Groovy表达式都可以插入所有字符串文字中,除了singletriple-single-quoted字符串。

  2. 您不能直接在Shell步骤中设置Groovy变量。从Groovy到Shell,这仅在一个方向上起作用。但是,您可以设置退出代码,并通过为参数sh传递truereturnStatus步骤返回该代码:

    stage('HelloWorld') {
        var = sh script: 'exit 42', returnStatus: true
        echo "$var"   // prints 42
    }
    

    如果数据更复杂,则可以将true传递给参数returnStdout,使用Shell脚本中的echo输出数据并解析从sh步骤返回的字符串:

    stage('HelloWorld') {
        var = sh script: "echo 'the answer is 42'", returnStdout: true
        echo "$var"   // prints "the answer is 42"  
    }
    
© www.soinside.com 2019 - 2024. All rights reserved.