如何在外部bash脚本中使用全局groovy变量

时间:2017-11-24 08:10:24

标签: bash groovy

这就是我在groovy中所拥有的:

sh 'echo "'+params.TEST+'"'
echo params.TEST

两者都回归' hello world'这就是我所期待的。 现在我想在外部bash脚本test.sh中使用该变量:

#!/bin/bash
echo "'+params.TEST+'"

我延长了我的groovy脚本:

sh 'echo "'+params.TEST+'"'
echo params.TEST
sh './test.sh'

但是最后一个命令,脚本的执行不是打印我的参数。我在这里错过了什么?我怎样才能让它发挥作用

2 个答案:

答案 0 :(得分:2)

您可以尝试将其作为参数传递给shell脚本,例如。

sh 'echo "'+params.TEST+'"'
echo params.TEST
sh './test.sh "' +params.TEST + '"'

并将shell脚本中的参数用作

#!/bin/bash
echo $1

答案 1 :(得分:0)

每当您运行外部脚本时,您的环境都将从父进程继承。这里有两个选择:

  • 创造一个全新的环境(可能有风险,因为你可以忘记一些事情)
  • 根据父母的
  • 创建新环境

在这两种情况下,您都需要操纵Map<String, String>并将变量添加到新环境中。

Groovy脚本(ProcessBuilder):

8< --- CUT HERE --- CUT HERE --- CUT HERE --- CUT HERE --- 

def script = "./file.sh"
def pb = new ProcessBuilder(script).inheritIO()

def variable = "Variable value"

Map<String, String> env = pb.environment()
env.put( "variable", variable )

Process p = pb.start()
p.waitFor()

8< --- CUT HERE --- CUT HERE --- CUT HERE --- CUT HERE ---

Groovy脚本(执行方法):

8< --- CUT HERE --- CUT HERE --- CUT HERE --- CUT HERE ---

def script = "./file.sh"

def variable = "Variable value"

myenv = new HashMap(System.getenv())
myenv.put("variable", variable )

String[] envarray = myenv.collect { k, v -> "$k=$v" }

def std_out = new StringBuilder()
def std_err = new StringBuilder()

proc = script.execute( envarray, null )

proc.consumeProcessOutput(std_out, std_err)

println std_out

8< --- CUT HERE --- CUT HERE --- CUT HERE --- CUT HERE ---

Shell脚本:

8< --- CUT HERE --- CUT HERE --- CUT HERE --- CUT HERE ---

#!/bin/bash

echo "Hello from script"
echo $variable

8< --- CUT HERE --- CUT HERE --- CUT HERE --- CUT HERE ---