Run an os command, redirecting its output to a file

I’d like to run an OS command that outputs to stdin, passing in the program to run and its arguments, along with some environment variables that I want to set first.

System.cmd lets me do all that. For example:

System.cmd(“my_command”, [“a”, “b”, “c”], env: [{“env1”, “val1”}, {“env2”, “val2”}] )

But since my_command can produce hundreds of megabytes of output, I don’t want to capture and return it back to elixir. Instead, I want to redirect its output to a file that I can post-process.

What is the recommended way to redirect the output of the run command to a file?

Cheers – Michael W

Output redirection is a shell feature, so you’re going to have to pass the command to a shell for execution. Assuming you’re on a Unix-style OS with Bash you could do something like:

System.cmd("bash", ["-c", "ls >tmp.txt"], env: my_env)!("tmp.txt")

Replace “bash” with “sh” or whatever, as needed.


BTW, as the System.cmd/3 docs point out, Erlang’s :os.cmd executes in an OS shell by default.

Many thanks!

One could also use the :into option of System.cmd.

1 Like

How do you use it ? I can’t make it work.

What have you tried? And what do you want to do exactly?

Here is what I’ve tried:
System.cmd("pg_dump", ["ulangan_dev"], into: "backup.sql")

I want to make a dump of my database into a file in my local folder.

You need a File.Stream to write to.

System.cmd("pg_dump", ~w[ulangan_dev], into:!("backup.sql"))

Something like this.


Amazing !!! Thank you !!! :slight_smile: