Search code examples
bashpipestdin

How to make a bash function which can read from standard input?


I have some scripts that work with parameters, they work just fine but i would like them to be able to read from stdin, from a pipe for example, an example, suppose this is called read:

#!/bin/bash
function read()
{
 echo $*
}

read $*

Now this works with read "foo" "bar", but I would like to use it as:

echo "foo" | read

How do I accomplish this?


Solution

  • You can use <<< to get this behaviour. read <<< echo "text" should make it.

    Test with readly (I prefer not using reserved words):

    function readly()
    {
     echo $*
     echo "this was a test"
    }
    
    $ readly <<< echo "hello"
    hello
    this was a test
    

    With pipes, based on this answer to "Bash script, read values from stdin pipe":

    $ echo "hello bye" | { read a; echo $a;  echo "this was a test"; }
    hello bye
    this was a test