Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Run shell commands in Elixir

Tags:

elixir

I want to execute a program through my Elixir code. What is the method to call a shell command to a given string? Is there anything which isn't platform specific?

like image 609
Lahiru Avatar asked Mar 23 '14 18:03

Lahiru


2 Answers

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.

like image 116
Overbryd Avatar answered Oct 19 '22 17:10

Overbryd


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 
like image 26
田咖啡 Avatar answered Oct 19 '22 17:10

田咖啡