0

My code is :

#!/bin/bash
while true; do
 COUNTER=$((COUNTER +1)) 
 echo $COUNTER
 if (($COUNTER%3 == 0)); then
 echo "Counter now is 3"
 sleep 2
 fi
 if (($COUNTER%6 == 0)); then
 echo "Counter now is 6"
 sleep 2
 fi
 if (($COUNTER%9 == 0)); then
 echo "Counter now is 9"
 sleep 2
 fi
 if (($COUNTER%12 == 0)); then
 echo "Counter now is 12"
 sleep 2
 fi
 if (($COUNTER%15 == 0)); then
 echo "Counter now is 15"
 sleep 2
 exit
 fi
done

and my output is :

./test2.sh 
1
2
3
Counter now is 3
4
5
6
Counter now is 3
Counter now is 6
7
8
9
Counter now is 3
Counter now is 9
10
11
12
Counter now is 3
Counter now is 6
Counter now is 12
13
14
15
Counter now is 3
Counter now is 15

Why is it showing, every time, Counter now is 3 or sometime show more on echo. I don't want it to show additional on echo

ctrl-alt-delor
28.7k10 gold badges66 silver badges112 bronze badges
asked Apr 5, 2018 at 8:56
2
  • 4
    Because 6,9,12 and 15 are also multiples of 3 Commented Apr 5, 2018 at 8:59
  • ... if you want to make it work in the intended way, then re-order the conditions so that you test from largest modulus to smallest and add a continue statement at the bottom of each test Commented Apr 5, 2018 at 12:26

2 Answers 2

1

It would be more correct if your outputs said what the corresponding test tested for, e.g.

if (( COUNTER%3 == 0 )); then
 echo 'COUNTER is a multiple of 3'
fi

This is the test that you have, and if you think about it, 6, 9, 12, and 15 are also multiples of 3.

In this short script, I would suggest that you test directly on COUNTER rather than on COUNTER%somevalue if you want to check the actual value of the counter rather than whether it's a multiple of some value:

if (( COUNTER == 3 )); then
 echo 'COUNTER is 3'
fi

Note that $ is not needed on variables when they are used in an arithmetic context.

answered Apr 5, 2018 at 9:18
0

Because output is a lie.

  • What is output when it says "count is..."?
  • What would be a better text than "Count is"?
  • Where does it echo count? (make it echo count is ...)

When you have fixed that, you should understand what it is doing.

answered Apr 5, 2018 at 9:40

You must log in to answer this question.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.