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.

import System.Environment (setEnv, getEnv, getEnvironment)
import Data.List.Split (splitOn)

main :: IO ()
main = do
    -- To set a key/value pair, use `setEnv`.
    -- To get a value for a key, use `getEnv`.
    -- `getEnv` will throw an exception if the key isn't present in the environment.
    setEnv "FOO" "1"
    foo <- getEnv "FOO"
    putStrLn $ "FOO: " ++ foo
    
    -- For safe access, you can use `lookupEnv` which returns `Maybe String`
    bar <- lookupEnv "BAR"
    putStrLn $ "BAR: " ++ maybe "" id bar

    -- Use `getEnvironment` to list all key/value pairs in the environment.
    -- This returns a list of tuples (key, value).
    putStrLn ""
    env <- getEnvironment
    mapM_ (putStrLn . fst) env

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

$ runhaskell environment-variables.hs
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 runhaskell environment-variables.hs
FOO: 1
BAR: 2
...

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.