【问题标题】:Is it possible to use "test" before "while read" in pipeline?是否可以在管道中“读取时”之前使用“测试”?
【发布时间】:2016-08-28 09:26:18
【问题描述】:

我有这样的管道:

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

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

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

【问题讨论】:

  • 你想用test完成什么?

标签: bash while-loop pipeline


【解决方案1】:

您可以使用process substitution

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 --

【讨论】:

    【解决方案2】:

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

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

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

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

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

    【讨论】:

    • 我倾向于同意,除非示例中的 do... 更改了 $number 的值,在这种情况下,条件无论如何都是错误的。
    【解决方案3】:

    我将使用seq 20 | paste - - - - 作为您的“管道”来生成一些每行 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
    

    【讨论】:

      猜你喜欢
      • 2010-11-03
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-01-23
      • 2018-07-29
      • 1970-01-01
      • 2022-07-25
      相关资源
      最近更新 更多