Environment Variables in Haskell
In this post we will go over how to accept environmental variables in Haskell.
import System.Environmentmain :: IO ()main = do
We can compile this if we put it in a file called
and run it with an ad-hoc ENV variable:
Which will print out:
but this will throw an error if the ENV var doesn’t exist:
λ ./envenv: myvariable: getEnv: does not exist (no environment variable)
To solve that issue we can use
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"mydefaultvalue"λ myvariable="what" ./env"what"