0

Let's say the following code:

myfunc() {
    cat grep "\->"  | while read line
    do
        echo $line
    done
}

ls -la | myfunc

It will work since you only cat once as you can only read once from stdin. But if you:

myfunc() {
    cat grep "\->"  | while read line
    do
        echo "a"
    done

    cat grep "\->"  | while read line
    do
        echo "b"
    done
}

ls -la | myfunc

which will generate the same output as 1st example does. So here, we will like to see how we can store stdin as a variable.

Let's try:

myfunc() {        
    tmp="$(cat)"
    # or: tmp=${*:-$(</dev/stdin)}
    echo $tmp
}

ls -la | myfunc

which gives total 32 drwxr-xr-x 9 phil staff 306 Sep 11 22:00 . 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 -rw-r--r-- 1 phil staff 0 Sep 11 22:00 t1 -rw-r--r-- 1 phil staff 0 Sep 11 22:00 t2 -rw-r--r-- 1 phil staff 0 Sep 11 22:00 t3 -rwxr-xr-x 1 phil staff 72 Sep 11 22:27 test.sh

which doesn't keep the original format of ls. May I ask that how shall I properly store stdin into a local var s.t, I can use it as

myfunc() {
    # TODO: store stdin into a var `tmp` exactly as it is (with \n)

    echo $tmp | grep "\->"  | while read line
    do
        echo "a"
    done

    echo $tmp | grep "\->"  | while read line
    do
        echo "b"
    done
}

ls -la | myfunc
Tom Lau
  • 109
  • 1
  • 7

1 Answers1

0

It's being stored fine. Echoing it is what's breaking it, since you're not quoting it. Change echo $tmp to echo "$tmp".