There are many discussions on this: Pipe output to bash function
I just want to know why:
#bin/sh
function myfunc () {
echo $1
}
ls -la | myfunc
will give empty line. May I ask that why isn't our output of ls
not treated as $1
as the function? What is the mechanism behind this?
If we try:
#bin/sh
function myfunc () {
i=${*:-$(</dev/stdin)}
echo $i
}
ls -la | myfunc
Then we have:
total 32 drwxr-xr-x 6 phil staff 204 Sep 11 21:18 . drwx------+ 17 phil staff 578 Sep 10 21:34 .. lrwxr-xr-x 1 phil staff 2 Sep 10 21:35 s1 -> t1 lrwxr-xr-x 1 phil staff 2 Sep 10 21:35 s2 -> t2 lrwxr-xr-x 1 phil staff 2 Sep 10 21:35 s3 -> t3 -rwxr-xr-x 1 phil staff 96 Sep 11 21:39 test.sh
which does not keep the actual format of ls -la
(with \n).
What is the correct/proposed way to pass a command output to your function as a parameter as it is?
Thanks
Update +John Kugelman
#bin/sh
function myfunc () {
cat | grep "\->" | while read line
do
echo $line
done
cat | grep "\->" | while read line
do
echo "dummy"
done
}
ls -la | myfunc
This will only print once. What if we would like to use the result twice (store it as a variable possible?)
Thanks,