在bash function中使用两次stdin

新手上路,请多包涵

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

Thanks!

阅读 1.6k
撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进