BASH Arithmetic Issues

arithmetic-expressions, bash

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

Problem

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.

Original source