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

JBoy picture JBoy · Sep 12, 2013 · Viewed 87.1k times · Source

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?

Answer

fedorqui 'SO stop harming' picture fedorqui 'SO stop harming' · Sep 12, 2013

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