在Bash循环内递增变量 [英] Incrementing a variable inside a Bash loop
问题描述
我正在尝试编写一个小的脚本,该脚本将对日志文件中的条目进行计数,并且在循环完成后递增要使用的变量(USCOUNTER
).
I'm trying to write a small script that will count entries in a log file, and I'm incrementing a variable (USCOUNTER
) which I'm trying to use after the loop is done.
但是在那一刻,USCOUNTER
看起来是0,而不是实际值.知道我在做什么错吗?谢谢!
But at that moment USCOUNTER
looks to be 0 instead of the actual value. Any idea what I'm doing wrong? Thanks!
FILE=$1
tail -n10 mylog > $FILE
USCOUNTER=0
cat $FILE | while read line; do
country=$(echo "$line" | cut -d' ' -f1)
if [ "US" = "$country" ]; then
USCOUNTER=`expr $USCOUNTER + 1`
echo "US counter $USCOUNTER"
fi
done
echo "final $USCOUNTER"
它输出:
US counter 1
US counter 2
US counter 3
..
final 0
推荐答案
您在子Shell中使用USCOUNTER
,这就是为什么变量未显示在主Shell中的原因.
You are using USCOUNTER
in a subshell, that's why the variable is not showing in the main shell.
仅执行while ... done < $FILE
,而不是cat FILE | while ...
.这样,您可以避免我在管道循环中设置变量的常见问题.为什么它们在循环终止后消失了?或者,为什么我不能通过管道读取数据?:
Instead of cat FILE | while ...
, do just a while ... done < $FILE
. This way, you avoid the common problem of I set variables in a loop that's in a pipeline. Why do they disappear after the loop terminates? Or, why can't I pipe data to read?:
while read country _; do
if [ "US" = "$country" ]; then
USCOUNTER=$(expr $USCOUNTER + 1)
echo "US counter $USCOUNTER"
fi
done < "$FILE"
请注意,我还用$()替换了"表达式.
Note I also replaced the `` expression with a $().
我也用while read country _
替换了while read line; do country=$(echo "$line" | cut -d' ' -f1)
.这样您可以说出while read var1 var2 ... varN
,其中var1
包含该行中的第一个单词,$var2
,依此类推,直到$varN
包含其余内容.
I also replaced while read line; do country=$(echo "$line" | cut -d' ' -f1)
with while read country _
. This allows you to say while read var1 var2 ... varN
where var1
contains the first word in the line, $var2
and so on, until $varN
containing the remaining content.
这篇关于在Bash循环内递增变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!