docs/reference-manual/native-image/guides/access-environment-variables.md
A native executable accesses environment variables in the same way as a regular Java application.
For example, run a Java application that iterates over your environment variables and prints out the ones that contain the String of characters passed as a command-line argument.
Make sure you have installed a GraalVM JDK. The easiest way to get started is with SDKMAN!. For other installation options, visit the Downloads section.
Save the following source code in a file named EnvMap.java:
import java.util.Map;
public class EnvMap {
public static void main (String[] args) {
var filter = args.length > 0 ? args[0] : "";
Map<String, String> env = System.getenv();
for (String envName : env.keySet()) {
if(envName.contains(filter)) {
System.out.format("%s=%s%n",
envName,
env.get(envName));
}
}
}
}
Compile the file and build a native executable, as follows:
javac EnvMap.java
native-image EnvMap
Run the native application and pass a command-line argument, such as "HELLO". There should be no output, because there is no environment variable with a matching name.
./envmap HELLO
<no output>
Create a new environment variable named "HELLOWORLD" and give it the value "Hello World!". (If you are using a bash shell, follow the example below.) Now, run the native executable again—it will correctly print out the name and value of the matching environment variable(s).
export HELLOWORLD='Hello World!'
./envmap HELLO
You should receive the expected output:
HELLOWORLD=Hello World!