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.

**Table of Contents**Expand

## 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:

**Direct arithmetic expressions**:`echo $((19 % 5))`

**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
```

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**.

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
```

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.

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
```

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.

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
```

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).

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
```

**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**

**Mastering 10 Essential Options of If Statement in Bash****How to Check a Boolean If True or False in Bash [Easy Guide]****Bash Test Operations in ‘If’ Statement****Check If a Variable is Empty/Null or Not in Bash [5 Methods]****Check If a Variable is Set or Not in Bash [4 Methods]****Check If Environment Variable Exists in Bash [6 Methods]****How to Use “OR”, “AND”, “NOT” in Bash If Statement [7 Examples]****Evaluate Multiple Conditions in Bash “If” Statement [2 Ways]****Using Double Square Brackets “[[ ]]” in If Statement in Bash****6 Ways to Check If a File Exists or Not in Bash****How to Check If a File is Empty in Bash [6 Methods]****7 Ways to Check If Directory Exists or Not in Bash****Negate an “If” Condition in Bash [4 Examples]****Check If Bash Command Fail or Succeed [Exit If Fail]****How to Write If Statement in One Line? [2 Easy Ways]****Different Loops with If Statements in Bash [5 Examples]****Learn to Compare Dates in Bash [4 Examples]**

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