Elixir EScript pass echo to script

Hey, I am trying to set up an elixir escript for a simple script.

I want to pass a result from echo using Linux pipe.

Here is an example:
echo -e '1234' | ./script argument

However in main script function:

  def main(args) do

when inspecting args I see only:
["argument"] instead of ["1234", "argument"]

Would appreciate your help or any resources.

1 Like

In Elixir, when you pass input through Linux pipe to an escript, the piped input will be available as command-line arguments starting from the second element of the args list. The first element of args will always be the name of the script itself.

Here’s how you can access the piped input in your main script function:

defmodule MyScript do
  def main(args) do
    # The first argument is the name of the script itself
    # The second argument (index 1) will be the piped input
    # The rest of the arguments (index 2 and beyond) will be any other arguments you pass after the pipe
    [piped_input | other_args] = args

    IO.inspect(piped_input)  # This will print the piped input
    IO.inspect(other_args)   # This will print the other arguments after the pipe

This doesn’t seem to work for me. With your example, it shows:

"a" in piped_input variable
[] in other_args variable

I found it:
The pipe operator passes the data as stdin so you need to do IO.read(:stdio, :line) in main to read it.


IIRC linux pipes pass info to the next process via STDIN, so I think you need some function from IO module to read it, for example:

defmodule MyScript do
  def main(args) do
    IO.inspect(args, label: "Args")

    Enum.each(IO.stream(:stdio, :line), &IO.write("stdio: #{&1}"))

You found the anwser while I was looking at Elixir docs :+1: