Use stdin twice in bash function

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)"
    -sharp 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 .

question: May I ask that how shall I properly store stdin into a local var s.t, I can use it as

myfunc() {
    -sharp 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

ThanksThanks!

Jun.11,2021
Menu