Bash Multiplication

In Bash scripting, you can perform arithmetic multiplication using arithmetic expansion, the expr command, and the let command. Multiplication is a basic arithmetic operation that allows you to calculate the product of two or more numbers.

In this tutorial, we’ll guide you through the different methods of performing multiplication in Bash with detailed examples and scenarios.

Bash Multiplication is one of the Arithmetic Operations in Bash.


Syntax for Multiplication in Bash

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

Multiplication using Arithmetic Expansion:

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

Multiplication using expr:

</>
Copy
expr a \* b

Multiplication using let:

</>
Copy
let product=a*b

Multiplication using bc (for floating-point multiplication):

</>
Copy
echo "a * b" | bc

Examples of Multiplication in Bash

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


1 Bash Multiplication Using Arithmetic Expansion

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

example.sh

</>
Copy
#!/bin/bash

# Define two numbers
num1=5
num2=4

# Perform multiplication
product=$((num1 * num2))

# Display the result
echo "The product of $num1 and $num2 is $product."

Output