Search code examples
elixirstdinelixir-mix

How to unix pipe the output of one command into Elixir's Mix Task?


I want to "pipe" the output of the cat command into an Elixir Mix Task and hold it in a variable as a binary.

I have already tried using the IO.gets/1, but it reads just the first line of the output.

cat textfile.txt | mix print
defmodule Mix.Tasks.Print do
  use Mix.Task

  def run(_argv) do
    Task.async(fn -> IO.gets("") end)
    |> Task.await(t)
    |> IO.puts() # prints the first line
  end
end

I want to get hold of the whole file's contents in a binary variable in Elixir and print it to the console, but I get just the first line. I'd expect Elixir to have some built-in solution, to end on EOF.


Solution

  • There is a IO.read/2 function I was looking for.

    defmodule Mix.Tasks.Print do
      use Mix.Task
    
      def run(_argv) do
        IO.read(:all)
        |> IO.puts() # prints all lines
      end
    end