Run shell commands in Elixir

Solution 1:

Here is how you execute a simple shell command without arguments:

System.cmd("whoami", [])
# => {"lukas\n", 0}

Checkout the documentation about System for more information.

Solution 2:

System.cmd/3 seems to accept the arguments to the command as a list and is not happy when you try to sneak in arguments in the command name. For example

System.cmd("ls", ["-al"]) #works, while
System.cmd("ls -al", []) #does not.

What in fact happens underneath is System.cmd/3 calls :os.find_executable/1 with its first argument, which works just fine for something like ls but returns false for ls -al for example.

The erlang call expects a char list instead of a binary, so you need something like the following:

"find /tmp -type f -size -200M |xargs rm -f" |> String.to_char_list |> :os.cmd