Incrementing a variable inside a Bash loop

2019-03-17 04:06发布

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.

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"

It outputs:

US counter 1
US counter 2
US counter 3
..
final 0

标签: bash shell loops
8条回答
啃猪蹄的小仙女
2楼-- · 2019-03-17 04:50

minimalist

counter=0
((counter++))
echo $counter
查看更多
狗以群分
3楼-- · 2019-03-17 04:51

You're getting final 0 because your while loop is being executed in a sub (shell) process and any changes made there are not reflected in the current (parent) shell.

Correct script:

while read -r country _; do
  if [ "US" = "$country" ]; then
        ((USCOUNTER++))
        echo "US counter $USCOUNTER"
  fi
done < "$FILE"
查看更多
登录 后发表回答