Environment Variables in Wolfram Language

Our program demonstrates how to work with environment variables. Environment variables are a universal mechanism for conveying configuration information to programs. Let’s look at how to set, get, and list environment variables.

(* To set a key/value pair, use Environment["key"] = "value". 
   To get a value for a key, use Environment["key"]. 
   This will return $Failed if the key isn't present in the environment. *)

Environment["FOO"] = "1";
Print["FOO: ", Environment["FOO"]];
Print["BAR: ", Environment["BAR"]];

(* Use Environment[] to list all key/value pairs in the environment. 
   This returns an association. Here we print all the keys. *)

Print[];
keys = Keys[Environment[]];
Print /@ keys;

Running the program shows that we pick up the value for FOO that we set in the program, but that BAR is $Failed (Mathematica’s equivalent of not found or null).

FOO: 1
BAR: $Failed

PATH
SHELL
USER
HOME
...
FOO

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 Mathematica, you can set environment variables before running the script using the SetEnvironment function:

SetEnvironment["BAR" -> "2"];
<< "environment-variables.m"

This would produce output like:

FOO: 1
BAR: 2
...

In Mathematica, environment variables persist only for the duration of the kernel session. To set environment variables that persist beyond the current session, you would need to modify system settings outside of Mathematica.