BASH Arithmetic problems

I work at BASH and right now I have an idiot moment. I have a project that I am working on and I will need to use some very basic arithmetic expressions and I just realized that many of my problems stem from my variables not being updated. So I put 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 am running a script. Doing nothing. I set up <

in >

just for kicks and an infinite loop occurs with re-entry:

1
0
1
0

      

Forever and ever, until I stop him. Therefore, it is obvious that the variables do not change. What for? I feel like such an idiot because it must be something stupid that I don't pay attention to. And why, when I have it <

, is it also not an endless loop? Why doesn't it print at all? If it's counter2

always less than 10, why doesn't it go on forever?

Thanks people in advance.

EDIT: I understand why it didn't output anything when checking <

... I would use $counter2

instead just counter2

to get the actual value counter2

, But now it just outputs:

1
2

      

And what is it ... I feel so derp.

+3


source to share


3 answers


If this is all bash (100% sure), you can use declare -i

to explicitly set the type of your variables, and then your code is 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 double-parentese arithmetic comparison. So, your time can be written as:

while (($counter2 <  10)) ; do

      

+4


source


Inside, $((...))

do not use the sigil ( $

).



counter2=$((counter2+counter))

      

+4


source


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

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

      

You will often find this construct more attractive to use:

for counter2 in {0..9}
do
    echo $counter": "$counter2
done

      

+1


source







All Articles