Bash Modulo

In Bash scripting, the **modulo** operation, represented by the % symbol, is used to find the remainder when one number is divided by another. The modulo operation is particularly useful when you need to check divisibility, find even or odd numbers, or perform cyclic calculations.

In this tutorial, we will explore different methods of performing the modulo operation in Bash using arithmetic expansion, the expr command, and practical examples.

For a quick overview of the Arithmetic Operations in Bash, you may refer Bash Arithmetic Operations.


Syntax for Modulo in Bash

The syntax for performing the modulo operation in Bash can vary depending on the method used. Here are the common approaches:

Modulo using Arithmetic Expansion:

</>
Copy
$((a % b))

Modulo using expr:

</>
Copy
expr a % b

Examples of Modulo in Bash

Let’s go through different examples to see how the modulo operation can be performed using these methods.


1 Bash Modulo Using Arithmetic Expansion

Arithmetic expansion is the simplest and most common way to perform the modulo operation in Bash. It uses the $((...)) syntax to evaluate the expression.

example.sh

</>
Copy
#!/bin/bash

# Define two numbers
num1=10
num2=3

# Perform modulo operation
remainder=$((num1 % num2))

# Display the result
echo "The remainder when $num1 is divided by $num2 is $remainder."

Output