Environment Variables in Julia

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 Julia.

using Base.Env

# To set a key/value pair, use `ENV[]`. To get a
# value for a key, use `ENV[]`. This will return
# nothing if the key isn't present in the environment.
ENV["FOO"] = "1"
println("FOO: ", get(ENV, "FOO", ""))
println("BAR: ", get(ENV, "BAR", ""))

# Use `ENV` to access all key/value pairs in the
# environment. Here we print all the keys.
println()
for (key, _) in ENV
    println(key)
end

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

$ julia environment-variables.jl
FOO: 1
BAR: 

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 julia environment-variables.jl
FOO: 1
BAR: 2
...

In Julia, environment variables are accessed through the ENV dictionary. Setting a variable is done by assigning a value to a key in ENV, and getting a value is done by accessing ENV with the key. The get function is used to provide a default value if the key doesn’t exist.

To list all environment variables, we can simply iterate over the ENV dictionary. Each entry in ENV is a key-value pair, so we use destructuring in the for loop to get just the keys.

Julia’s approach to environment variables is quite similar to other high-level languages, providing a straightforward way to interact with the system’s environment.