Environment Variables in Groovy

Environment variables are a universal mechanism for conveying configuration information to Unix programs. Let’s look at how to set, get, and list environment variables in Groovy.

// To set a key/value pair, use System.setProperty()
// To get a value for a key, use System.getenv()
// This will return null if the key isn't present in the environment
System.setProperty("FOO", "1")
println "FOO: ${System.getenv('FOO')}"
println "BAR: ${System.getenv('BAR')}"

// Use System.getenv() without arguments to get all environment variables
// This returns a Map of strings in the form KEY=value
// Here we print all the keys
println()
System.getenv().each { key, value ->
    println key
}

Running the program shows that we pick up the value for FOO that we set in the program, but that BAR is null.

FOO: 1
BAR: null

The list of keys in the environment will depend on your particular machine.

TERM_PROGRAM
PATH
SHELL
...
FOO

If we set BAR in the environment first, the running program picks that value up.

$ BAR=2 groovy environment-variables.groovy
FOO: 1
BAR: 2
...

In Groovy, we use System.setProperty() to set environment variables within the program, and System.getenv() to retrieve them. The System.getenv() method returns a Map when called without arguments, allowing us to iterate over all environment variables.

Note that changes made using System.setProperty() are only visible to the current Java process and its child processes. They do not affect the system-wide environment variables.