Environment Variables in Elixir
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 Elixir.
Running the program shows that we pick up the value for FOO
that we set in the program, but that BAR
is nil.
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 Elixir, environment variables are accessed through the System
module. The System.put_env/2
function is used to set environment variables, while System.get_env/1
is used to retrieve them. If a variable doesn’t exist, System.get_env/1
returns nil
instead of an empty string.
To list all environment variables, we use System.get_env/0
which returns a map. We then use Map.keys/1
to get all the keys and Enum.each/2
to print each one.
This example demonstrates how to interact with environment variables in Elixir, which is a common task in configuration management and system interaction.