Environment Variables in Erlang

Our program demonstrates how to work with environment variables in Erlang. 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.

-module(environment_variables).
-export([main/0]).

main() ->
    % To set a key/value pair, use os:putenv/2. To get a
    % value for a key, use os:getenv/1. This will return
    % an empty string if the key isn't present in the
    % environment.
    os:putenv("FOO", "1"),
    io:format("FOO: ~s~n", [os:getenv("FOO")]),
    io:format("BAR: ~s~n", [os:getenv("BAR")]),

    % Use os:env/0 to list all key/value pairs in the
    % environment. This returns a list of tuples in the
    % form {Key, Value}. Here we print all the keys.
    io:format("~n"),
    lists:foreach(
        fun({Key, _}) ->
            io:format("~s~n", [Key])
        end,
        os:env()
    ).

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

$ erl -noshell -s environment_variables main -s init stop
FOO: 1
BAR: 

TERM_PROGRAM
PATH
SHELL
...
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.

$ BAR=2 erl -noshell -s environment_variables main -s init stop
FOO: 1
BAR: 2
...

In Erlang, we use the os module to interact with environment variables. The os:putenv/2 function is used to set environment variables, while os:getenv/1 is used to retrieve them. The os:env/0 function returns all environment variables as a list of key-value tuples.

Note that in Erlang, strings are represented as lists of integers, so we use "~s" in the format string of io:format/2 to print them as readable strings.