tcoopman

tcoopman

Run a shell command with a pipe operator

I’m trying to run a shell command with a pipe operator in it. For example “sleep 0.1 | echo foo”. At first I tried to do this with System.cmd:

System.cmd("sleep", ["0.1", "|", "echo", "foo"])

But this results in /usr/bin/sleep: invalid time interval '|', invalid time interval 'echo'....

So next I tried to use :os.cmd:

:os.cmd("sleep 0.1 | echo foo")

But whatever I do to execute this I get:

:os.cmd("sleep 0.1 | echo foo")
** (FunctionClauseError) no function clause matching in :os.validate/1    
    
    The following arguments were given to :os.validate/1:
    
        # 1
        "sleep 0.1 | echo foo"
    
    (kernel) os.erl:281: :os.validate/1
    (kernel) os.erl:237: :os.cmd/1

Looking into the code of :os (https://github.com/erlang/otp/blob/master/lib/kernel/src/os.erl) is see that :os.validate expects atoms? But in the erlang docs there are no atoms used (http://erlang.org/doc/man/os.html)

Marked As Solved

tcoopman

tcoopman

I’ve just been able to solve my own problem.
If I do: os.cmd(:"sleep 0.1 | echo foo") it works.

So I need to pass an atom to os.cmd.

Also Liked

alco

alco

I made a mistake in the invocation. To evaluate a string in sh, the -c has to be passed first:

System.cmd("sh", ["-c", "sleep 0.1"])
idi527

idi527

Or :os.cmd('sleep 0.1 | echo foo').

iex(1)> :os.cmd('sleep 0.1 | echo foo')
'foo\n'

It works with atoms and character lists. Doesn’t seem to work with binaries.

I would try to avoid creating new atoms for each command you might want to run since they are not garbage collected.

benwilson512

benwilson512

Author of Craft GraphQL APIs in Elixir with Absinthe

System.cmd does not run a shell, so pipes, redirects, and so on aren’t supported. System.cmd is basically the closest thing that Elixir has to fork.

:os.cmd is definitely handy, but take great care if any of the stuff in your command comes from users (like filenames). You risk letting users run arbitrary programs.

alco

alco

It is strange that :os.cmd accepts an atom for the command name, looks like a historical accident.

In general, functions from the Erlang standard library take character lists where in Elixir you would use a string. To make it more confusing, the Erlang type for such lists is called string(). I recommend taking a look at this cheat sheet if you still feel confused.

Going back to your problem, Ben has already done a good job explaining the difference between Elixir’s System.cmd and Erlang’s :os.cmd. In the source code for :os.cmd you can see it actually spawns a shell appropriate for the current OS and evaluates the string you’ve passed to the function in that shell.

Replicating this behaviour for your particular example using System.cmd is easy:

System.cmd("sh", ["sleep 0.1 | echo foo"])
OvermindDL1

OvermindDL1

Not entirely. A lot of the ‘base’ functions get the string value of atoms, it makes it cheap and efficient to pass around something like sed instead of having to do "sed" in the original erlang (plus it’s fantastic since atoms in erlang can have @ in them without quoting too!). Calling other programs was generally used to access their stdin/stdout, not for argument parsing and ‘doing’ other stuff. :slight_smile:

(Do note, the sed and "sed" above in erlang, in elixir would be :sed and 'sed' respectively.)

Where Next?

Popular in Questions Top

vonH
In asking this question I am more interested about the expressiveness of the language itself and less concerned about the availability of...
New
New
hariharasudhan94
I would like to know what is the best IDE for elixir development?
New
Phillipp
Hey, I have a NanoPi-M3 and try to install Elixir on their Ubuntu image. I followed the Raspberry Pi installation instructions from the ...
New
makeitrein
Hey all, just started picking up Elixir last week and am writing a scraper as a learning project. Baby step #1 is extracting the number ...
New
shahryarjb
Hello, I have map which I want to convert it to string like this: the map: %{last_name: "tavakkoli", name: "shahryar"} the string I ne...
New
electic
Hi, I am new to Elixir. I am trying to use the DateTime component to insert a date into MySQL however the there seems to be no way to fo...
New
chewm
Hi guys, nice to meet you to the whole forum, I’m new here, I’m trying to configure visual studio code for elixir, right now the intellis...
New
sabri
Can someone explain the settings of pool_size of Ecto in config file? and what is the recommend size? Thanks
New
joeerl
Hello again - after a longish gap I’ve decided I really must dig into Elixir and see what’s been happening here - so I have a few questio...
New

Other popular topics Top

chrismccord
Phoenix 1.4.0 released Phoenix 1.4 is out! This release ships with exciting new features, most notably with HTTP2 support, improved deve...
688 30048 115
New
sergio_101
I am VERY much an elixir newbie. I have taken one elixir course and one phoenix course on Udemy. During that course, I saw the instructor...
New
_russellb
I want to try my hand at web scraping. What tools/libraries do I need to use. I’m hoping to turn this into something professional so don’...
New
malloryerik
Hi, this is for people who, like me, have had some friction using .html.heex templates in VSCode. The solution seems to be, in a hyphena...
New
lk-geimfari
What is most correct way to open, read and parse JSON file with poison? For example if we have example.json file in root of some projec...
New
mcarvalho
What is the difference between System.get_env and Application.get_env? For example, what are best practices to use one versus another.
New
mgjohns61585
Could someone help me? I'm making my first elixir program, number guessing game. I can't figure out how to convert the user's guess from ...
New
fayddelight
I tried installing elixir 1.11.2 erlang 23.3.4 via asdf in my zsh shell. Enabled the versions locally and globally. When I list them ...
New
fireproofsocks
Forgive me if this is obvious, but how does one delete a database record WITHOUT selecting it first? https://hexdocs.pm/ecto/Ecto.Repo.h...
New
TunkShif
This post is an instruction guide to help you setup your Neovim for Elixir development from scratch. It includes general information on h...
273 38985 115
New

We're in Beta

About us Mission Statement