while循环的输入来自`command`的输出

Fel*_*rez 18 shell loops while-loop

#I used to have this, but I don't want to write to the disk
#
pcap="somefile.pcap"
tcpdump -n -r $pcap > all.txt
while read line; do  
  ARRAY[$c]="$line"
  c=$((c+1))  
done < all.txt  
Run Code Online (Sandbox Code Playgroud)

以下无法正常工作.

# I would prefer something like...
#
pcap="somefile.pcap"
while read line; do  
  ARRAY[$c]="$line"
  c=$((c+1))  
done < $( tcpdump -n -r "$pcap" )
Run Code Online (Sandbox Code Playgroud)

在谷歌搜索结果太少(不明白,我想找到:(什么的).我想保持它Bourne兼容(/ bin/sh的),但它并不具备如此.

Ama*_*dan 21

这是sh兼容的:

tcpdump -n -r "$pcap" | while read line; do  
  # something
done
Run Code Online (Sandbox Code Playgroud)

但是,sh没有数组,所以你不能拥有像它一样的代码sh.别人都在说正确的都bashperl是时下相当普遍的,你可以在他们是可用非古系统大都数.

更新以反映@Dennis的评论

  • 请注意,由于这使用了管道,因此一旦 while 循环存在,在 while 循环内创建的任何变量将不可用(因为管道创建了一个子 shell)。如果您对仅在 bash 中有效的东西感到满意,您可以使用[进程替换](http://mywiki.wooledge.org/ProcessSubstitution)提供输入,就像[这个答案](https://stackoverflow.html)中一样。 com/a/2983261/6157047)。 (3认同)
  • 除了Bourne shell没有数组.并且,在Bash中,循环体中的两条线(OK,OP的循环)可以折叠成:`ARRAY [$ c] + =("$ line")`或`ARRAY [c ++] ="$ line "`.但管道+1为'while`. (2认同)

Ign*_*ams 18

这适用于bash:

while read line; do  
  ARRAY[$c]="$line"
  c=$((c+1))  
done < <(tcpdump -n -r "$pcap")
Run Code Online (Sandbox Code Playgroud)

  • sh不能使用`<(...)`进程替换语法. (4认同)