Home » Scripting and Automation » Bash / Shell Scripts » Shell script for using modulo operator, finding if number is dividable and print remainder.

Shell script for using modulo operator, finding if number is dividable and print remainder.

Following shell script helps to understand how to use modulo operator in bash and identify if number is completely dividable by another number and print the remainder.
This script accepts two arguments on the commands line, first number is Divident and second number is Divisor.

 $ vim understanding_modulo_operator.sh 
#!/bin/bash
NUMBER=$1
DIVIDE_BY=$2
remainder=$((NUMBER%DIVIDE_BY))
echo "Module operation of $NUMBER%$DIVIDE_BY is $remainder"

if [ $remainder == "0" ]
then
    echo "$NUMBER: is completely dividable by $DIVIDE_BY"
else
    echo "$NUMBER: is not dividable by $DIVIDE_BY"
fi

Now, lets assume we want to divide 10 by 2 first and 10 by 3 next.

$ bash understanding_modulo_operator.sh 10 2
Module operation of 10%2 is 0
10: is completely dividable by 2
$ bash understanding_modulo_operator.sh 10 3 
Module operation of 10%3 is 1
10: is not dividable by 3

Subscribe our Rurban Life YouTube Channel.. "Rural Life, Urban LifeStyle"

Leave a Comment