Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Incrementing a variable inside a Bash loop

Tags:

bash

shell

loops

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 
like image 918
maephisto Avatar asked Dec 19 '13 11:12

maephisto


People also ask

How do you increment a variable in a bash script?

Increment Bash Variable with += Operator Another common operator which can be used to increment a bash variable is the += operator. This operator is a short form for the sum operator. The first operand and the result variable name are the same and assigned with a single statement.

Can you use ++ in bash?

Similar to other programming language bash also supports increment and decrement operators. The increment operator ++ increases the value of a variable by one.

What is $@ in bash?

bash [filename] runs the commands saved in a file. $@ refers to all of a shell script's command-line arguments. $1 , $2 , etc., refer to the first command-line argument, the second command-line argument, etc. Place variables in quotes if the values might have spaces in them.

What is $1 and $2 in bash?

$1 is the first argument (filename1) $2 is the second argument (dir1)


1 Answers

You are using USCOUNTER in a subshell, that's why the variable is not showing in the main shell.

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 $().

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.

like image 119
fedorqui 'SO stop harming' Avatar answered Nov 15 '22 22:11

fedorqui 'SO stop harming'