在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!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论