Bash Modulo Operations in “If” Statement [4 Examples]

The modulo operation with an if statement in Bash states the process of computing the remaining (leftover) value after dividing one integer by another. The modulo (%) operator used in this process is so flexible that it can perform operations in different contexts such as data partitioning, remainder finding, circular buffer generation, load balancing, distributing tasks, and operating time and date calculations.

In this article, I will illustrate 4 practical examples of modulo operations in the ‘if’ condition in Bash.

What is Modulo in Bash?

Modulo is a binary operation that calculates the remainder of a division between two integers. In Bash, the modulo operator (abbreviated as mod) is denoted by the symbol % and is also referred to as the remainder operator. It is an essential resource for integer arithmetic in Bash scripts. The syntax of the modulo operator is:

Remainder = Dividend % Divisor

Or,

expr Dividend % Divisor

Where ‘Dividend’ and ‘Divisor’ are two integer numbers.

There are two ways to use the modulo (%) operator in Bash scripting. They are:

  1. Direct arithmetic expressions:
    echo $((19 % 5))
  2. With variable assignments:
    x=15
    y=4
    echo $((x % y))

Order of Precedence

The precedence of an operator determines the sequence in which it is evaluated in an expression. In Bash, the modulo (%) operator has the same order of precedence as the multiplication (*) and division (/) operators. However, you can use parentheses to enclose the operation that you want to evaluate first to override the precedence of any operator.

4 Examples of Modulo Operations in Bash “If” Condition

Following are some examples dictating how the modulo operation can be performed in various scenarios across Bash scripting for tasks related to even or odd data checking, divisible number checking, leap year checking, and cyclical pattern generating.

Example 1: Checking for Odd or Even Number

To check if a number is odd or even, use the modulo (%) operator with 2 as a divisor. If the result is zero (0) i.e. there is no remainder, the number is even. But if the division process leaves the remainder of 1, the number is odd.

Use the syntax if ((number % 2 == 0)); to perform a check on assigned numbers if it is odd or even. For example:

#!/bin/bash

#Defining a variable
x=4

#Checking if ‘x’ is even
if ((x % 2 == 0)); then
echo "$x is even."
fi
#Defining another variable
y=7

#Checking if ‘y’ is odd
if ! ((y % 2 == 0)); then
echo "$y is odd."
fi

EXPLANATION

In the script, if ((x % 2 == 0)); checks whether the remainder is equal to zero. If the condition is satisfied, the script executes the number as even. Besides, if ! ((y % 2 == 0)); using the negation (!) operator checks similarly as if ((x % 2 == 0)); but reverses the output i.e. verifies if the remainder is not equal to zero. If the condition is met, the script executes the number as odd.

Checking if the given numbers are odd or even

As you can see from the image above, I have assigned 4 and 7 to x and y respectively. Since 4 % 2 equals 0 (no remainder) and 7 % 2 equals 1 (the remainder is not 0), it prints that ‘x’ is even and ‘y’ is odd.

Example 2: Checking if a Number is Divisible

As the modulo (%) operator evaluates the remainder of a division operation, so if the remainder is zero, it indicates that the number inserted as a dividend is divisible by the divisor. Otherwise, the number is not divisible. Let’s see an example:

#!/bin/bash

echo "Enter the dividend: "
read x

echo "Enter the divisor: "
read y

#Checking if x is divisible by y
if ((x % y == 0)); then
echo "$x is divisible by $y."
fi

EXPLANATION

Here, if ((x % y == 0)); using the modulo (%) operator checks if the remainder of x divided by y is equal to zero. If the condition is true, it means x is truly divisible by y and the script echoes an output message.

Checking if a number is divisible by another

According to the above image, the condition ((24 % 8 == 0)) becomes true i.e. implies that the dividend 24 is divisible by the divisor 8.

Example 3: Checking for Leap Year

To check if a year is a leap year, you can append the modulo operation in Bash. Generally, there is a leap year every four (4) years i.e. the year can be divided by 4, except for years that are divisible by 100 but not by 400.

So, to do a leap year check, you can use the syntax if (( (year % 4 == 0 && year % 100 != 0) || (year % 400 == 0) )); and see the following script:

#!/bin/bash

echo "Enter a year: "
read year

#Checking if it is a leap year
if (( (year % 4 == 0 && year % 100 != 0) || (year % 400 == 0) )); then
echo "Yes! $year is a leap year."
fi

EXPLANATION

The if condition checks if the year inserted here is divisible by 4 and not divisible by 100, or it is divisible by 400. If the conditions are satisfied, the script displays an output showing that the year is a leap year; otherwise, the year is not a leap year.

Checking if the given year '2032' is a leap year

You can see from the above image that the year ‘2032’ I have entered is a leap year.

Example 4: Generating Cyclic Patterns

Generating cyclic patterns using the modulo (%) operator refers to creating a repeating sequence based on remainders when dividing a series of numbers by a fixed divisor.

Here’s an example demonstrating the generation of a cyclic pattern (1 to 12) based on their remainders when divided by 2.

#!/bin/bash

#Defining the range for the sequence
range=12

echo "Cyclic Pattern from 1 to $range:"

for ((n = 1; n <= range; n++)); do
if ((n % 2 == 0)); then #Checking if the remainder is 0
echo "Number: $n | Remainder 0"
elif ((n % 2 == 1)); then #Checking if the remainder is 1
echo "Number: $n | Remainder 1"
fi
done

EXPLANATION

In this script, the for loop is used to iterate through numbers from 1 to 12. Inside the loop, if ((n % 2 == 0)); and elif ((n % 2 == 1)); calculate if the remainder is 0 and 1 respectively when dividing the current number n by 2. If the conditions are met, the script displays the specified outputs with a cyclic pattern of remainders (0, 1).

Creating a cyclic pattern ranging from 1 to 12

The above image illustrates that the result is a sequence of numbers 0 and 1 that repeats after a certain interval.

Conclusion

To sum up, you have looked at several modulo operations under the ‘if’ condition in Bash. Try to practice them more often and enhance your scripts’ readability.

People Also Ask

Can the modulo operator handle negative numbers in Bash?

Yes, the modulo operator can handle negative numbers in Bash. But sometimes the result may vary in different versions of Bash. So, when dealing with negative numbers, it’s recommended to verify the behavior of the modulo operation in your Bash environment.

Is the Bash modulo operator efficient for large computations?

No, the Bash mod operator is not efficient for large computations because of the complexity of its underlying computation.

Can I nest if statements with modulo operations in Bash?

Yes, you can nest if statements with modulo operations in Bash and make hierarchical decisions based on the different remainders.

Can the modulo operator assist in data partitioning or segmentation within Bash scripts?

Yes, the modulo operator can assist in data partitioning or segmentation within Bash scripts. A simple example to demonstrate data segmentation using the modulo operator:

#!/bin/bash

#Partition number
num_part=3

#Data range (IDs from 1 to 15)
start=1
end=15

echo "Data segmentation from $start to $end into $num_part segments:"

#Looping through the data range
for ((id = start; id <= end; id++)); do
segment=$((id % num_part)) #Data segmentation using modulo
echo "ID: $id | Segment: $segment"
done

Can the modulo operator be utilized for date or time-related calculations in Bash scripts?

Yes, the modulo operator can be utilized for date or time-related calculations in Bash scripts such as finding intervals, elapsed times, leap years, calculating minutes, hours, days etc.

Can the modulo operator handle floating-point numbers in Bash?

No, the modulo (%) operator does not support floating-point numbers directly except integers in Bash. However, if you want to perform a modulo-like operation on floating-point numbers, you can employ external utilities like bc, awk etc. But this is not a straightforward method like the modulo operation with integers. Here’s an example:

#!/bin/bash

#Using ‘awk’ for modulo-like operation on floating-point numbers
remainder=$(echo "6.3" | awk '{printf "%f", $1 - int($1 / 3) * 3}')
echo "Remainder: $remainder"

Are there any limitations to using the modulo operator in Bash?

Yes, there is a major limitation to using the modulo operator in Bash; that is a division-by-zero error. To avoid such potential errors, always ensure that the divisor is not zero.

Related Articles


<< Go Back to If Statement in Bash | Bash Conditional Statements | Bash Scripting Tutorial

Rate this post
LINUX
FUNDAMENTALS
A Complete Guide for Beginners Enroll Course Now
icon linux
Nadiba Rahman

Hello, This is Nadiba Rahman, currently working as a Linux Content Developer Executive at SOFTEKO. I have completed my graduation with a bachelor’s degree in Electronics & Telecommunication Engineering from Rajshahi University of Engineering & Technology (RUET).I am quite passionate about crafting. I really adore exploring and learning new things which always helps me to think transparently. And this curiosity led me to pursue knowledge about Linux. My goal is to portray Linux-based practical problems and share them with you. Read Full Bio

Leave a Comment