Shell脚本的Groovy参数 [英] Groovy parameter to shell script

查看:413
本文介绍了Shell脚本的Groovy参数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我一直试图将我的代码分成两个不同的文件:callTheFunction.groovytheFunction.groovy.

I've been trying to separate my code into two different files: callTheFunction.groovy and theFunction.groovy.

从文件名中可以​​看到:

As you can see from the name of the file:

  • callTheFunction.groovy调用theFunction.groovy中定义的函数,将随机值作为参数传递.
  • theFunction是一个shell脚本-groovy函数内部-应该使用从callTheFunction传递的参数.
  • callTheFunction.groovy calls the function defined in theFunction.groovy, passing random values in as parameters.
  • theFunction is a shell script - inside groovy function - which is supposed to use the parameters passed from callTheFunction.

问题:
Shell脚本无法识别/理解参数,变量为空,没有值.

PROBLEM:
The shell script does not recognize/understand the arguments, the variables are empty, no value.

Function.groovy

def call(var1, var2) {
  sh '''
    echo "MY values $var1 and $var2"
  '''
}

callTheFunction.groovy

def call {
  pipeline {
    stages {
      stage ('myscript') {
        steps {
          theFunction("Value1", "Value2")
        }
      }
    }
  }
}

从管道输出:

MY values  and

我知道那里也有类似的问题:

I am aware that there are similar issues out there:

  • Pass groovy variable to shell script
  • How to assign groovy variable to shell variable

推荐答案

更新

您可以使用环境变量而无需environment {}

You can use environment variable without having environment {}

使用类似我在这里使用的环境变量(我对您的代码进行了一些重构).对外壳程序脚本使用三重单引号进行循环并向其添加grrovy变量:

Use environment variables like the ones i have used here (i refactored your code a little bit). Using triple single quotes for shell script for loop and adding grrovy variable to it:

def callfunc() {
  sh '''
  export s="key"
  echo $s
  for i in $VARENV1 
    do
      echo "Looping ... i is set to $i"
    done
    '''
}

pipeline {
    agent { label 'agent_1' }
    stages {
      stage ('Run script') {
        steps {
            script {
                env.VARENV1 = "Peace"
            }
            callfunc()
        }
      }
    }
}

输出:

参考: Jenkins-将参数传递给groovy函数

这篇关于Shell脚本的Groovy参数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆