【发布时间】:2012-11-23 11:41:44
【问题描述】:
我想计算给定目录中的所有 *bin 文件。最初我使用的是for-loop:
var=0
for i in *ls *bin
do
perform computations on $i ....
var+=1
done
echo $var
但是,在某些目录中,文件过多导致错误:Argument list too long
因此,我尝试使用管道while-loop:
var=0
ls *.bin | while read i;
do
perform computations on $i
var+=1
done
echo $var
现在的问题是使用管道创建了子壳。因此,echo $var 返回0。
我该如何处理这个问题?
原代码:
#!/bin/bash
function entropyImpl {
if [[ -n "$1" ]]
then
if [[ -e "$1" ]]
then
echo "scale = 4; $(gzip -c ${1} | wc -c) / $(cat ${1} | wc -c)" | bc
else
echo "file ($1) not found"
fi
else
datafile="$(mktemp entropy.XXXXX)"
cat - > "$datafile"
entropy "$datafile"
rm "$datafile"
fi
return 1
}
declare acc_entropy=0
declare count=0
ls *.bin | while read i ;
do
echo "Computing $i" | tee -a entropy.txt
curr_entropy=`entropyImpl $i`
curr_entropy=`echo $curr_entropy | bc`
echo -e "\tEntropy: $curr_entropy" | tee -a entropy.txt
acc_entropy=`echo $acc_entropy + $curr_entropy | bc`
let count+=1
done
echo "Out of function: $count | $acc_entropy"
acc_entropy=`echo "scale=4; $acc_entropy / $count" | bc`
echo -e "===================================================\n" | tee -a entropy.txt
echo -e "Accumulated Entropy:\t$acc_entropy ($count files processed)\n" | tee -a entropy.txt
【问题讨论】:
-
for循环在 shell 中进行评估,因此它本身不会产生“参数列表太长”。也许您可以返回该代码并修复那里的其他任何错误。 (*ls看起来像是错位了;也许最初的问题是 useless use ofls?)