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.
Running the program shows that we pick up the value for FOO
that we set in the program, but that BAR
is null.
The list of keys in the environment will depend on your particular machine.
If we set BAR
in the environment first, the running program picks that value up.
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.