How do I execute a list of commands in Haskell?

Viewed 282

I'm new to Haskell and I have been using system to execute shell commands for me, since I'm only interested in exit status. I noticed that since I can do something like:

ls <- system "ls"
pwd <- system "pwd"

and this correctly executes the two commands. I was thinking about executing an array of these commands eg

lsAndPwd <- return $ system <$> ["ls", "pwd"]

and I'm surprised that this doesn't actually execute anything. This compiles and I checked that lsAndPwd has the correct type of [IO GHC.IO.Exception.ExitCode] but the commands are never executed. What's going on and how can I get this to work?

1 Answers

You should use mapM instead of <$> so you get an IO [ExitCode], not an [IO ExitCode]. This way, it's collected into one IO monad that you can run:

lsAndPwd <- mapM system ["ls", "pwd"]

Alternatively, call sequence on the whole thing:

lsAndPwd <- sequence $ system <$> ["ls", "pwd"]
Related