Bash: How to Check if Number is Divisible by Another Number


You can use the following syntax in Bash to check if a number is divisible by another number:

if [ $(( $num % 5)) -eq 0 ]
then
    echo "Number is divisible by 5"
else
    echo "Number is not divisible by 5"
fi

This particular example checks if the number stored in the variable named num is divisible by 5 and outputs one of the following strings as a result:

  • “Number is divisible by 5”
  • “Number is not divisible by 5”

Note that we use the logic $(( $num % 5)) -eq 0 to check if the number divided by 5 produces a remainder equal to zero.

If the remainder produced is equal to zero then the number is divisible by 5.

Otherwise, the number is not divisible by 5.

The following example shows how to use this syntax in practice.

Example: Check if Number is Divisible by Another Number in Bash

Suppose we have a variable named num with a value of 20 in Bash.

We can use the following syntax to check if this number is divisible by 5:

num=20

if [ $(( $num % 5)) -eq 0 ]
then
    echo "Number is divisible by 5"
else
    echo "Number is not divisible by 5"
fi

The following screenshot shows how to use this syntax in practice:

Bash check if number is divisible by another number

This returns “Number is divisible by 5” since the variable named num contains the value 20, which is indeed divisible by 5.

Suppose instead that our variable named num has a value of 16.

We can use the following syntax to check if this number is divisible by 5:

num=16

if [ $(( $num % 5)) -eq 0 ]
then
    echo "Number is divisible by 5"
else
    echo "Number is not divisible by 5"
fi

The following screenshot shows how to use this syntax in practice:

Bash if else statement to check if number is divisible

This returns “Number is not divisible by 5” since the variable named num contains the value 16, which is indeed not divisible by 5.

Note: Feel free to return any text you’d like as output in the if else statement.

Related Tutorials

The following tutorials explain how to perform other common tasks in Bash:

Bash: How to Generate a Sequence of Numbers
Bash: How to Check if Number is Within a Range
Bash: How to Check if Number is Even or Odd
Bash: How to Round Numbers to 2 Decimal Places

Leave a Reply