Question

I'm working in BASH and I'm having an idiot moment right now. I've got a project I'm working on that I'm going to need to use some very basic arithmetic expressions and I just realized that a lot of my problems with it are because my variables are not updating. So I threw together a basic algorithm that increments a variable by another variable with a while loop until a certain number is reached.

counter=1
counter2=0

while [[ counter2 < 10 ]]; do
   counter2=$(($counter2+$counter))
   echo $counter
   echo $counter2
done 

I run the script. Does nothing. I set the < to > just for kicks and an infinite loop occurs with a repeated output of:

1
0
1
0

Forever and ever until I stop it. So it's obvious the variables are not changing. Why? I feel like such an idiot because it must be something stupid I'm overlooking. And why, when I have <, it also isn't an infinite loop? Why doesn't it print anything at all for that matter? If counter2 is always less than 10, why doesn't it just keep going on forever?

Thanks folks in advance.

EDIT: Well, I realize why it wasn't outputting anything for when the check is <... I should have been using $counter2 instead of just counter2 to get the actual value of counter2. But now it just outputs:

1
2

And that's it... I feel like such a derp.

Was it helpful?

Solution

If this is all bash (100% sure) then you could use declare -i in order to explicitly set type of your variables and then your code will be as simple as :

declare -i counter=1
declare -i counter2=0

while [[ $counter2 -lt 10 ]]; do
   counter2=$counter2+$counter
   echo $counter
   echo $counter2
done

EDIT: In bash, you can do arithmatic comparison with double paranethesis. So, your while can be written as:

while (($counter2 <  10)) ; do

OTHER TIPS

Inside the $((...)), don't use the sigil ($).

counter2=$((counter2+counter))

In bash, you can use c-like for loops:

for (( counter2=0; counter2<10; counter2+=counter ))
do
   echo $counter": "$counter2
done

Often you will find this construct more appealing to use:

for counter2 in {0..9}
do
    echo $counter": "$counter2
done
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top