Reputation: 7317
Consider the following Haskell function:
eraseFile :: FilePath -> IO ()
eraseFile basename =
do let cmd' = ">"
args' = ("/path/to/file/" ++ basename) :: String
(exitcode', stdout', stderr') <- readProcessWithExitCode cmd' [args'] ""
return ()
When I try to run this in a stack ghci
repl, or from the main function, I get a permission denied
error from the console. Normally, in a bash console, you could just run this command as sudo
, but this doesn't seem to work when invoked from Haskell.
Question: How to execute system commands in Haskell as root?
Upvotes: 0
Views: 265
Reputation: 120711
As already pointed out in the comments, you can just run the entire stack/ghc under root, but I daresay that's a bad idea. Preferrably, I'd just invoke sudo
as a process from within your program. The particular command – emptying a file, if I have understood that correctly? – is then easiest done with tee
:
do let cmd' = "sudo"
args' = ["tee", "/path/to/file/" ++ basename :: String]
(exitcode', stdout', stderr') <- readProcessWithExitCode cmd' args' ""
As Zeta remarks, truncate --size 0
would probably be a cleaner command.
To get around password entering, you probably also want to make an exception in the sudoers
file. It's a hairy matter; of course the really best thing would be if you could avoid needing root permissions altogether.
Upvotes: 2