Calling shell process from Groovy script

If you want to run shell script from Groovy, you can easily achieve that using either ProcessBuilder or execute methods.

If you want to access environment variable (created inside Groovy) there are two ways:

– create completely new environment – risky, you can forget some essential variables
– create new environment based on parent’s one – preferred, simply add new variables

In both cases you need to manipulate Map<String, String> in order to add variables into environment.

Let’s say we want to run following code


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

#!/bin/bash

echo "Hello from script"

# variable called "variable" must be defined inside environment
echo $variable

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

we can either use ProcessBuilder


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

// In this case I use ProcessBuilder class and inheritIO method
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 ---

or, we can use execute method. It takes two arguments – environment (List) and execution directory name.

8< --- CUT HERE --- CUT HERE --- CUT HERE --- CUT HERE --- def script = "./file.sh" def variable = "Variable value" // we have to create HashMap from HashMap here! // Note the result of method! // // https://docs.oracle.com/javase/7/docs/api/java/lang/System.html#getenv() // // "Returns an unmodifiable string map view of the current system environment." // myenv = new HashMap(System.getenv()) myenv.put("variable", variable ) // we have to convert to array before calling execute 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 ---

Leave a comment

Your comment