Bash Addition

In Bash scripting, you can perform arithmetic addition using arithmetic expansion, the expr command, and the let command.

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

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


Syntax for Addition in Bash

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

Addition using Arithmetic Expansion:

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

Addition using expr:

</>
Copy
expr a + b

Addition using let:

</>
Copy
let sum=a+b

Addition using bc (for floating-point addition):

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

Examples of Addition in Bash

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


1 Bash Addition Using Arithmetic Expansion

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

example.sh

</>
Copy
#!/bin/bash

# Define two numbers
num1=10
num2=20

# Perform addition
sum=$((num1 + num2))

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

Output