How do I exit BASH while loop using modulus operator?

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

3 Answers

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

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.)

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"
$

Your Answer

Sign up or log in

Sign up using Google Sign up using Facebook Sign up using Email and Password

Post as a guest

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

You Might Also Like