input of while loop to come from output of `command`

為{幸葍}努か 提交于 2019-12-03 12:08:37

问题


#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  

The following fails to work.

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

Too few results on Google (doesn't understand what I want to find :( ). I'd like to keep it Bourne-compatible (/bin/sh), but it doesn't have to be.


回答1:


This is sh-compatible:

tcpdump -n -r "$pcap" | while read line; do  
  # something
done

However, sh does not have arrays, so you can't have your code like it is in sh. Others are correct in saying both bash and perl are nowadays rather widespread, and you can mostly count on their being available on non-ancient systems.

UPDATE to reflect @Dennis's comment




回答2:


This works in bash:

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



回答3:


If you don't care about being bourne, you can switch to Perl:

my $pcap="somefile.pcap";
my $counter = 0;
open(TCPDUMP,"tcpdump -n -r $pcap|") || die "Can not open pipe: $!\n";
while (<TCPDUMP>) {
    # At this point, $_ points to next line of output
    chomp; # Eat newline at the end
    $array[$counter++] = $_;
}

Or in shell, use for:

for line in $(tcpdump -n -r $pcap)  
do  
 command  
done  



回答4:


for line in $(tcpdump -n -r $pcap)  
do  
 command  
done 

This isn't exactly doing what I need. But it is close. And Shell compatible. I'm creating HTML tables from the tcpdump output. The for loop makes a new <tr> row for each word. It should make a new row for each line (\n ending). Paste bin script01.sh.



来源:https://stackoverflow.com/questions/2983213/input-of-while-loop-to-come-from-output-of-command

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!