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 env.hs
.
ghc env.hs
and run it with an ad-hoc ENV variable:
myvariable="what" ./env
Which will print out:
"what"
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 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"mydefaultvalue"λ myvariable="what" ./env"what"