简体   繁体   中英

Infinite Loop trouble bash

So, basically the code below is giving an infinite loop. However, if i change i+2 and f+2 to i++ and f++, they don't give an infinite loop. Can someone explain to me why this is? Thanks

#!/bin/bash
for ((i=0; i<5; i+2))
do
for ((f=0; f<5; f+2))
do
echo "$i $f"
done
done

You need to do += , not + (also, i+=2 should be f+=2 in your inner loop):

for ((i=0; i<5; i+=2))
do
    for ((f=0; f<5; f+=2))
    do
        echo "$i $f"
    done
done

i+2 does not change the value of i . It simply adds 2 to the current value of i and returns the result. i++ changes the value of i by incrementing it. Try this instead:

for ((i=0; i<5; i=i+2))

Note that i=i+2 can also be written shorthand as i+=2 . The meaning is the same: add 2 to the current value of i and assign the result to i .

+= syntax is short form so you could also represent i+=2 as i=i+2

for ((i=0; i<5; i+=2))
do
    for ((f=0; f<5; f+=2))
    do
        echo "$i $f"
    done
done

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM