up vote 1 down vote favorite
share [g+] share [fb]
#!/bin/bash


Echo “Enter a number”

Read  $number

If [$number ] ; then 

Echo “Your number is divisible by 5”

Else

Echo “Your number is not divisible by 5”

fi

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

link|improve this question
Welcome, Roger. Can you please wrap the code in your question in code tags (or use the code button on the editor)? It makes things a lot easier to read. – Telemachus Oct 1 '09 at 23:34
feedback

4 Answers

No bc needed as long as it's integer math (you'll need bc for floating point though): In bash, the (( )) operator works like expr.

As others have pointed out the operation you want is modulo (%).

#!/bin/bash  

echo "Enter a number"
read number

if [ $(( $number % 5 )) -eq 0 ] ; then
   echo "Your number is divisible by 5"
else
   echo "Your number is not divisible by 5"
fi
link|improve this answer
feedback

You can use a simpler syntax in Bash than some of the others shown here:

#!/bin/bash
read -p "Enter a number " number    # read can output the prompt for you.
if (( $number % 5 == 0 ))           # no need for brackets
then
    echo "Your number is divisible by 5"
else
    echo "Your number is not divisible by 5"
fi
link|improve this answer
thanks! i knew there had to be a simpler way but wasn't having any luck. bash scripting has always been a bit of a black art to me. – quack quixote Oct 4 '09 at 10:06
feedback

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
link|improve this answer
1  
Alternatively, you could use expr instead of bc: remainder=expr $number % $divisor – Dan Dyer Oct 1 '09 at 23:35
@Dan Yes it should suffice for the OP. However, I think since bc specialises in calculations, it can handle stuff like 33.3 % 11.1 which expr would likely choke on. – nagul Oct 1 '09 at 23:48
would definitely choke; expr and (( )) only handle integer math. – quack quixote Oct 2 '09 at 0:03
feedback

Nagul's answer is great, but just fyi, the operation you want is modulus (or modulo) and the operator is generally %.

link|improve this answer
feedback

Your Answer

 
or
required, but never shown