4

So practically for my assignment I need to break out of a true while loop when the user inputs a number that gives a modulus remainder of 0, ex: (25 % 5 = 0 break loop) Where in my attempt below have I gone wrong?

while true
do
    echo "Please input anything here: "
    read INPUT

    if [ `expr $INPUT % 5` -eq 0 ]; then
        echo "you entered wrong"
    else
        echo "you entered right"
        break
fi
done
2
  • 2
    If the assignment specifies bash, then you might consider using its built-in arithmetic expansion syntax e.g. (( INPUT % 5 == 0 )) Apr 2, 2019 at 18:45
  • the loop does not end when entering 25 @steeldriver Apr 2, 2019 at 18:50

3 Answers 3

7

Move the break from the else part to the if part:

#!/bin/bash

while true
do
    echo "Please input anything here: "
    read INPUT

    if [ `expr $INPUT % 5` -eq 0 ]; then
        echo "you entered wrong"
        break
    else
        echo "you entered right"
    fi
done
5
  • this doesn't work, when I enter 40 the code exits Apr 2, 2019 at 18:46
  • 6
    @RooseveltMendieta Isn't it what you want? I need to break out of a true while loop when the user inputs a number that gives a modulus remainder of 0. 40%5 is also 0.
    – Kulfy
    Apr 2, 2019 at 18:58
  • 2
    @Kulfy i was thinking of division in my head instead of modulus, how embarrassing lol yes this solution in fact does work and is exactly what I needed. I need to go to sleep i've been up to late working on this assignment. Apr 2, 2019 at 19:04
  • @RooseveltMendieta It seems that you changed the original code in your question. So, PerlDuck might need to modify explanation of the answer.
    – Kulfy
    Apr 2, 2019 at 19:07
  • i version controlled the code back to it's original state @Kulfy Apr 2, 2019 at 19:10
5

It works for me according to @steeldriver's tips,

  • make sure you use bash

    #!/bin/bash
    
  • use the bash syntax for arithmetic evaluation

    ((...))
    

Otherwise the shellscript can remain the same,

#!/bin/bash

while true
do
    echo "Please input anything here: "
    read INPUT

    if (( INPUT % 5 == 0 )) ; then
        echo "you entered right"
        break
    else
        echo "you entered wrong"
    fi
done

Edit: You have modified the question. This answer corresponds to a previous version of the question. (It is not clear to me, if you want to break the loop, when there is no remainder or when there is a remainder.)

4

Since this is bash script we're talking about, you may want to use read -p and arithmetic evaluation ((...))

$ while read -p "Enter number:" input ; do (( input%5 == 0 )) && { echo "Wrong"; break;} || echo "alright"; done
Enter number:11
alright
Enter number:7
alright
Enter number:10
Wrong

Portably, you might want to use [ aka test

$ [ $((25%5)) -eq 0 ]  && echo "Zero"
Zero
$ [ $((26%5)) -eq 0 ]  && echo "Zero"
$

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .