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
minimalist
You're getting
final 0
because yourwhile loop
is being executed in a sub (shell) process and any changes made there are not reflected in the current (parent) shell.Correct script: