在bash function中使用两次stdin

发布于 2022-09-07 22:30:12 字数 1690 浏览 35 评论 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

Thanks!

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。
列表为空,暂无数据
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文