Run shell commands in Elixir

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.


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

You can have a look in the Erlang os Module. E.g. cmd(Command) -> string() should be what you are looking for.

Tags:

Elixir