Environment Variables in Haskell

In this post we will go over how to accept environmental variables in Haskell.

import System.Environment
main :: IO ()
main = do

We can compile this if we put it in a file called env.hs.

ghc env.hs

and run it with an ad-hoc ENV variable:

myvariable="what" ./env

Which will print out:


but this will throw an error if the ENV var doesn't exist:

λ ./env
env: myvariable: getEnv: does not exist (no environment variable)

To solve that issue we can use lookupEnv with fromMaybe

import System.Environment (lookupEnv)
import Data.Maybe (fromMaybe)
main :: IO ()
main = do

which will give us a default value when the ENV variable doesn't exist:

λ ./env
λ myvariable="what" ./env

Join the Newsletter

My newsletter is where you'll find exclusive content from me. I write about technology, startups, and why you shouldn't call yourself a junior engineer

Web Mentions