是否可以在管道中的 "while read" 之前使用 "test"?

Is it possible to use "test" before "while read" in pipeline?

我有这样的管道:

pipeline | test $number -eq 3 && while read A B C D; do...; done 

但这不起作用,因为 while read 无法再从管道读取参数,因为 test $number -eq 3 &&

我该如何解决?我不能使用 awk 或 sed。

您可以使用 :

test $number -eq 3 && while read A B C D;
do
    ...
done < <(pipeline)

例如:

$ n=3
$ test $n -eq 3 && while read A B C; do echo "A: $A, B: $B, rest: $C --"; done < <(echo a b c d e f)
A: a, B: b, rest: c d e f --

在我看来,编写代码最清晰的方法是使用 if:

if test $number -eq 3; then
    pipeline | while read A B C D; do...; done
fi

如果你真的想用&&,那我猜你可以用这个:

test $number -eq 3 && pipeline | while read A B C D; do...; done

...但我个人认为不是很清楚。

我将使用 seq 20 | paste - - - - 作为你的 "pipeline" 生成一些每行 4 个单词的行。

这是你的问题:

$ seq 20 | paste - - - - | test $number -eq 3 && while read A B C D; do echo "A=$A B=$B C=$C D=$D"; done
^C

while 循环卡住等待 stdin 上的输入。

此修复只是将测试和循环组合在一起,因此 read 可以访问管道的输出:

$ seq 20 | paste - - - - | { test $number -eq 3 && while read A B C D; do echo "A=$A B=$B C=$C D=$D"; done; }
A=1 B=2 C=3 D=4
A=5 B=6 C=7 D=8
A=9 B=10 C=11 D=12
A=13 B=14 C=15 D=16
A=17 B=18 C=19 D=20