Home » Questions » Computers [ Ask a new question ]

How to make a statement that checks if something is divisible by something else without a remainder (BASH)

How to make a statement that checks if something is divisible by something else without a remainder (BASH)

the if [$number] statement is what I don't know how to set up

Asked by: Guest | Views: 45
Total answers/comments: 3
Guest [Entry]

"How about using the bc command:

!/usr/bin/bash

echo “Enter a number”
read number
echo “Enter divisor”
read divisor
remainder=`echo ""${number}%${divisor}"" | bc`
echo ""Remainder: $remainder""

if [ ""$remainder"" == ""0"" ] ; then
echo “Your number is divisible by $divisor”
else
echo “Your number is not divisible by $divisor”
fi"
Guest [Entry]

"Just in the interest of syntax neutrality and mending the overt infix notation bias around these parts, I've modified nagul's solution to use dc.

!/usr/bin/bash

echo “Enter a number”
read number
echo “Enter divisor”
read divisor
remainder=$(echo ""${number} ${divisor}%p"" | dc)
echo ""Remainder: $remainder""

if [ ""$remainder"" == ""0"" ]
then
echo “Your number is divisible by $divisor”
else
echo “Your number is not divisible by $divisor”
fi"
"Just in the interest of syntax neutrality and mending the overt infix notation bias around these parts, I've modified nagul's solution to use dc.

!/usr/bin/bash

echo “Enter a number”
read number
echo “Enter divisor”
read divisor
remainder=$(echo ""${number} ${divisor}%p"" | dc)
echo ""Remainder: $remainder""

if [ ""$remainder"" == ""0"" ]
then
echo “Your number is divisible by $divisor”
else
echo “Your number is not divisible by $divisor”
fi"
Guest [Entry]

"You could also use expr like so:

#!/bin/sh

echo -n ""Enter a number: ""
read number
if [ `expr $number % 5` -eq 0 ]
then
echo ""Your number is divisible by 5""
else
echo ""Your number is not divisible by 5""
fi"