Shell while循环的输入来自`命令的输出` #我以前有这个,但我不想写入磁盘 # pcap=“somefile.pcap” tcpdump-n-r$pcap>all.txt 读行时;做 数组[$c]=“$line” c=$((c+1)) 完成
以下方法不起作用Shell while循环的输入来自`命令的输出` #我以前有这个,但我不想写入磁盘 # pcap=“somefile.pcap” tcpdump-n-r$pcap>all.txt 读行时;做 数组[$c]=“$line” c=$((c+1)) 完成,shell,loops,while-loop,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 #我更喜欢像。。。 # pcap=“somefile.pcap” 读行时;做 数组[$c]=“
#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
#我更喜欢像。。。
#
pcap=“somefile.pcap”
读行时;做
数组[$c]=“$line”
c=$((c+1))
完成<$(tcpdump-n-r“$pcap”)
Google上的搜索结果太少(不明白我想找到什么:()。我想让它与Bourne兼容(/bin/sh),但不一定要兼容。如果你不在乎成为Bourne,你可以切换到Perl:
# I would prefer something like...
#
pcap="somefile.pcap"
while read line; do
ARRAY[$c]="$line"
c=$((c+1))
done < $( tcpdump -n -r "$pcap" )
这在bash中起作用:
for line in $(tcpdump -n -r $pcap)
do
command
done
读取行时;执行以下操作
数组[$c]=“$line”
c=$((c+1))
完成<
这并不是我所需要的。但是它很接近。并且与Shell兼容。我正在从tcpdump输出创建HTML表。for
循环为每个单词创建一个新行。它应该为每行创建一个新行(\n结尾)。
.这是兼容的:
for line in $(tcpdump -n -r $pcap)
do
command
done
然而,sh
没有数组,所以你不能像sh
那样拥有你的代码。其他人正确地说,bash
和perl
现在相当普遍,你可以指望它们在非古代系统上可用
更新以反映@Dennis的评论是的。它在Bash中工作。它为什么不在/bin/sh中运行?我想让脚本可移植。可移植性通常很重要吗?为了确保其他人也可以运行脚本,数组对sh也不可用。但是+1用于进程替换。@DW.不知道数组的名称在sh
中不支持。这不是个好兆头。我对这个有很高的期望,但它不会生成HTML文件!我不明白为什么。>>eek,我在里面留下了一个用于测试的“echo”。现在已修复,应该与您的相同。(顺便说一句,我想你的意思是,当你插入这个代码段时,你的代码不会生成HTML——这个代码段本身不会像你的代码段那样生成HTML),除了Bourne shell没有数组之外。在Bash中,循环体中的两行(好的,OP的循环)可以折叠成:ARRAY[$c]+=(“$line”)
或ARRAY[c++]=“$line”
。但是+1用于管道进入while
。请注意,由于这使用管道,while循环存在后,while循环内创建的任何变量都将不可用(因为管道创建子shell)。如果您对仅在bash中工作的内容没有意见,可以使用类似于的方式输入输入。您需要执行saveIFS=$IFS;IFS=$'\n';for循环;IFS=$saveIFS
,因为默认情况下,IFS
会导致空格、制表符和换行符上的内容中断。我今天将尝试此操作,并向您报告。在shell版本中,您需要设置仅将S转换为换行符,以便tcpdump
的输出不会在每个空格处中断。
while read line; do
ARRAY[$c]="$line"
c=$((c+1))
done < <(tcpdump -n -r "$pcap")
for line in $(tcpdump -n -r $pcap)
do
command
done
tcpdump -n -r "$pcap" | while read line; do
# something
done