Environment Variables in Haskell
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 Haskell.
Running the program shows that we pick up the value for FOO
that we set in the program, but that BAR
is empty.
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 Haskell, we use the System.Environment
module to work with environment variables. The setEnv
function is used to set a variable, getEnv
to retrieve a variable’s value, and getEnvironment
to get all environment variables.
Note that getEnv
will throw an exception if the variable doesn’t exist. For safer access, you can use lookupEnv
which returns a Maybe String
.
The splitOn
function from Data.List.Split
is used to split the “KEY=value” strings, similar to the strings.SplitN
function in the original example.
Remember to compile or run your Haskell program with the appropriate permissions to modify environment variables.