0
0
Bash Scriptingscripting~5 mins

Arithmetic expansion $(( )) in Bash Scripting

Choose your learning style9 modes available
Introduction
Arithmetic expansion lets you do math calculations inside your script easily.
When you want to add, subtract, multiply, or divide numbers in a script.
When you need to update a counter or index in a loop.
When you want to calculate values based on user input or variables.
When you want to perform simple math without calling external programs.
Syntax
Bash Scripting
result=$(( expression ))
The expression inside $(( )) can use +, -, *, /, %, and more.
No spaces are needed around the arithmetic operators, but they are allowed.
Examples
Adds 3 and 5, then prints 8.
Bash Scripting
sum=$((3 + 5))
echo $sum
Subtracts 1 from variable count and prints 9.
Bash Scripting
count=10
count=$((count - 1))
echo $count
Multiplies 4 by 7 and prints 28.
Bash Scripting
product=$((4 * 7))
echo $product
Finds remainder of 10 divided by 3 and prints 1.
Bash Scripting
remainder=$((10 % 3))
echo $remainder
Sample Program
This script calculates the area by multiplying length and width using arithmetic expansion.
Bash Scripting
#!/bin/bash

# Calculate the area of a rectangle
length=8
width=5
area=$((length * width))
echo "Area of rectangle: $area"
OutputSuccess
Important Notes
You can use variables inside $(( )) without the $ sign, like $((length * width)).
Arithmetic expansion only works with integers, not decimals.
You can use parentheses inside for grouping, like $(((2 + 3) * 4)).
Summary
Arithmetic expansion $(( )) lets you do math inside bash scripts easily.
Use it to calculate values, update counters, or perform math with variables.
It works only with whole numbers and supports common math operators.