Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

execute a command during every n-th iteration

Tags:

bash

I would like to print "is OK" during every odd loop iteration(first, third, fifth, etc) and print "is not OK" during every even loop iteration(second, fourth, sixth, etc). I'm able to accomplish this with:

$ for (( i=0,j=24,k=48; i<=200; i=i+48,j=j+48,k=k+48 )); do printf '%s\n%s\n' ""$i" to "$j" is OK" ""$j" to "$k" is not OK"; done
0 to 24 is OK
24 to 48 is not OK
48 to 72 is OK
72 to 96 is not OK
96 to 120 is OK
120 to 144 is not OK
144 to 168 is OK
168 to 192 is not OK
192 to 216 is OK
216 to 240 is not OK
$ 

However, is there a more elegant solution to accomplish the same?

like image 492
Martin Avatar asked Jan 19 '26 14:01

Martin


2 Answers

You can use the modulo operator % for that:

for (( i=0; i<200; i+=24 )); do
  echo -n "$i to $((i+24)) is "
  ((i % 48 != 0)) && echo -n "not "
  echo OK
done
like image 157
ooga Avatar answered Jan 21 '26 02:01

ooga


This code will output the same results as yours:

for (( i=0; i<=216; i+=24 )); do
    let j=i+24
    let v=(i/24)%2                           #calculate the iteration number
    if [ "$v" -eq 0 ]; then                  #if [ the iteration number is even ]
            printf ""$i" to "$j" is OK\n"
    else
            printf ""$i" to "$j" is not OK\n"
    fi
done
like image 44
elias-berg Avatar answered Jan 21 '26 03:01

elias-berg



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!