Arithmetic operations are a fundamental aspect of bash scripting, enabling scripts to perform calculations, automate tasks, and make decisions based on numerical data. Bash provides a variety of methods for performing arithmetic operations, from simple addition and subtraction to more complex calculations like floating-point operations and handling scientific numbers. This tutorial will guide you through different techniques and provide practical examples to enhance your bash scripting skills.
In this tutorial you will learn:
- Basic Arithmetic Operations in Bash
- Using External Tools for Advanced Calculations
- Applying Arithmetic in Loops and Conditional Statements
- Handling Floating-Point Numbers and Scientific Notation

Understanding Bash Arithmetic Operations
Bash supports various arithmetic operations. We’ll start with basic operations and then move to more advanced examples, demonstrating how Bash can be used for efficient and effective scripting.
- Basic Addition
#!/bin/bash a=10 b=5 sum=$((a + b)) echo "Sum: $sum"
This Bash script performs a simple arithmetic operation: addition. The first line
a=10
assigns the value 10 to the variablea
. Similarly, the second lineb=5
assigns the value 5 to the variableb
. The third linesum=$((a + b))
calculates the sum of the values held ina
andb
using the arithmetic expansion syntax$(( ))
, and assigns the result to the variablesum
. The last lineecho "Sum: $sum"
uses theecho
command to print the text “Sum: ” followed by the value of thesum
variable, effectively displaying the result of the addition (15 in this case) on the console. This script is a basic example of how to use variables and arithmetic in Bash to perform and display the result of a calculation.Simple addition of two numbers using the $((expression)) syntax. - Subtraction
#!/bin/bash a=10 b=5 difference=$((a - b)) echo "Difference: $difference"
This Bash script calculates the difference between two numbers. The line
a=10
assigns the value 10 to the variablea
. The next lineb=5
assigns the value 5 to the variableb
. The script then performs a subtraction operation withdifference=$((a - b))
, which subtracts the value ofb
froma
and assigns the result (5 in this case) to the variabledifference
.Finally, the script uses the
echo
command inecho "Difference: $difference"
to print out the phrase “Difference: ” followed by the calculated difference (5). This is a straightforward example of performing and displaying the result of a basic arithmetic operation in Bash.Subtracting one number from another using the $((expression)) syntax. - Multiplication
#!/bin/bash a=10 b=5 product=$((a * b)) echo "Product: $product"
This Bash script calculates the difference between two numbers. The line
a=10
assigns the value 10 to the variablea
. The next lineb=5
assigns the value 5 to the variableb
. The script then performs a subtraction operation withdifference=$((a - b))
, which subtracts the value ofb
froma
and assigns the result (5 in this case) to the variabledifference
.Lastly, the script uses the
echo
command inecho "Difference: $difference"
to print out the phrase “Difference: ” followed by the calculated difference (5). This is a straightforward example of performing and displaying the result of a basic arithmetic operation in Bash.Basic multiplication of two numbers. - Division
#!/bin/bash a=10 b=5 quotient=$((a / b)) echo "Quotient: $quotient"
This Bash script calculates the quotient of two numbers and displays the result. The script sets the value of
a
to 10 andb
to 5. The expressionquotient=$((a / b))
performs integer division ofa
byb
and assigns the result to the variablequotient
. Since botha
andb
are integers, anda
is 10 whileb
is 5, the division yields an integer quotient of 2.The final line
echo "Quotient: $quotient"
uses theecho
command to print the text “Quotient: ” followed by the value of thequotient
variable. In this case, it displays “Quotient: 2” on the console. This script is a simple example of how to perform division in Bash.Dividing one number by another. - Modulus Operation
#!/bin/bash a=15 b=4 modulus=$((a % b)) echo "Modulus: $modulus"
This Bash script calculates the modulus (remainder of division) of two numbers and displays the result. The first linea=15
assigns the value 15 to the variablea
. The second lineb=4
assigns the value 4 to the variableb
. The script then performs the modulus operation withmodulus=$((a % b))
, which calculates the remainder whena
is divided byb
. For the given values, the remainder of dividing 15 by 4 is 3, so this is the value assigned tomodulus
.The script outputs the result using
echo "Modulus: $modulus"
, which prints the string “Modulus: ” followed by the value ofmodulus
(3 in this case) to the console. This demonstrates the use of the modulus operator in Bash to find the remainder of a division operation.Finding the remainder(modulus) of a division operation. - Incrementing a Variable
#!/bin/bash counter=0 ((counter++)) echo "Incremented value: $counter"
This Bash script demonstrates how to increment (increase by one) the value of a variable. The script starts by setting
counter
to 0 withcounter=0
. The next line,((counter++))
, is an arithmetic expression that increments the value ofcounter
. In this context,++
is a post-increment operator, which means it increases the value ofcounter
by 1.After this operation, the value of
counter
becomes 1. Finally, the script displays the incremented value usingecho "Incremented value: $counter"
. This command prints the string “Incremented value: ” followed by the current value ofcounter
, which is 1. This example is a simple demonstration of using arithmetic expressions for incrementing a variable’s value in Bash.Using the increment (++) operator. - Decrementing a Variable
#!/bin/bash counter=10 ((counter--)) echo "Decremented value: $counter"
This Bash script demonstrates how to decrement (decrease by one) the value of a variable. The script initializes the variable
counter
with the value 10 usingcounter=10
. The next line,((counter--))
, employs an arithmetic expression that uses the post-decrement operator--
to reduce the value ofcounter
by 1. After this operation, the value ofcounter
becomes 9.The last line of the script,
echo "Decremented value: $counter"
, uses theecho
command to print the string “Decremented value: ” followed by the updated value ofcounter
. In this case, it displays “Decremented value: 9” on the console. This example illustrates the use of arithmetic expressions in Bash for decrementing a variable’s value.Using the decrement (–) operator. - Power Operation
#!/bin/bash base=2 exponent=3 power=$((base**exponent)) echo "Power: $power"
This Bash script calculates the power of a number and displays the result. The script begins by assigning the value 2 to the variable
base
and the value 3 to the variableexponent
using the linesbase=2
andexponent=3
, respectively. The next line,power=$((base**exponent))
, performs the power operation: it raisesbase
to theexponent
, which in this case calculates 2 raised to the power of 3.The result of this calculation, which is 8, is then stored in the variable
power
. Finally, the script outputs this result with theecho "Power: $power"
command, which prints the string “Power: ” followed by the value ofpower
(8 in this case) to the console. This example showcases how to perform exponentiation in a Bash script.Calculating the power of a number. - Using expr for Addition
#!/bin/bash a=10 b=5 sum=$(expr $a + $b) echo "Sum: $sum"
- Comparing Numbers in Conditional Statements
#!/bin/bash a=10 b=20 if ((a > b)); then echo "$a is greater than $b" elif ((a < b)); then echo "$a is less than $b" else echo "$a is equal to $b" fi
- Looping with Arithmetic Operations
#!/bin/bash for ((i = 1; i <= 5; i++)); do echo "Number $i" done
This Bash script demonstrates a for loop that iterates through a sequence of numbers. The loop is initialized with
for ((i = 1; i <= 5; i++));
, wherei
is set to start at 1, the conditioni <= 5
ensures the loop continues as long asi
is less than or equal to 5, andi++
incrementsi
by 1 in each iteration. Inside the loop, theecho "Number $i"
command is executed, which prints the current value ofi
prefixed with “Number “. The loop will iterate five times, printing “Number 1”, “Number 2”, …, up to “Number 5”. After the fifth iteration, wheni
becomes 6, the conditioni <= 5
becomes false, ending the loop.Using arithmetic operations in a for loop. - Floating-Point Arithmetic with bc
#!/bin/bash a=10.5 b=5.2 sum=$(echo "$a + $b" | bc) echo "Sum: $sum"
- Square Root Calculation
number=16 sqrt=$(echo "scale=2; sqrt($number)" | bc -l) echo "Square root of $number: $sqrt"
This Bash script calculates the square root of a number using the
bc
utility, which is a command-line calculator. The script assigns the value 16 to the variablenumber
withnumber=16
. The key operation,sqrt=$(echo "scale=2; sqrt($number)" | bc -l)
, usesecho
to send the commandsqrt($number)
(which becomessqrt(16)
) tobc
, specifying a scale of 2 to get the result with two decimal places.Thebc -l
command invokesbc
with the standard math library, which is necessary for the square root function. The calculated square root, 4.00, is then stored in the variablesqrt
. Finally,echo "Square root of $number: $sqrt"
prints the result, displaying “Square root of 16: 4.00”.Calculating the square root of a number using bc. - Natural Logarithm with bc
#!/bin/bash number=7 ln=$(echo "l($number)" | bc -l) echo "Natural logarithm of $number: $ln"
This Bash script calculates the natural logarithm of a number using the
bc
utility, which is enhanced with the-l
option to include the standard math library necessary for logarithmic calculations. The script starts by assigning the value 7 to the variablenumber
usingnumber=7
. The key operation,ln=$(echo "l($number)" | bc -l)
, sends the commandl($number)
(which becomesl(7)
) tobc
. This command computes the natural logarithm (base e) of 7.The result of this calculation is captured and stored in the variable
ln
using command substitution$(...)
. Finally, the script usesecho "Natural logarithm of $number: $ln"
to print the result, displaying the natural logarithm of 7, formatted as a floating-point number.Calculating the natural logarithm of a number. - Handling Scientific Numbers with awk
#!/bin/bash sum=$(awk 'BEGIN {print (1.23e2 + 3.45e3)}') echo "Sum: $sum"
This Bash script calculates the sum of two numbers in scientific notation using
awk
, a powerful text processing and arithmetic computation tool. The commandsum=$(awk 'BEGIN {print (1.23e2 + 3.45e3)}')
usesawk
to perform the addition of1.23e2
(which is 1.23×102, or 123) and3.45e3
(which is 3.45×103, or 3450).The
BEGIN
block in theawk
command ensures that the calculation is done immediately, without needing any input. The result of this addition, 3573, is then captured and stored in the variablesum
via command substitution$(...)
. Finally, the script outputs this result usingecho "Sum: $sum"
, which displays the string “Sum: ” followed by the value ofsum
(3573 in this case) to the console. This example showcases howawk
can be used for arithmetic operations, especially with numbers in scientific notation.Performing addition on scientific numbers using awk. - Calculating File Line Count
#!/bin/bash file="example.txt" line_count=$(wc -l < "$file") echo "The file $file has $line_count lines."
This Bash script counts the number of lines in a file and displays the result. The script sets the variable
file
to the name of the file to be processed, “example.txt”, usingfile="example.txt"
. It then uses the commandline_count=$(wc -l < "$file")
to count the lines.The
wc -l
command counts the number of lines in the file, and the redirection< "$file"
feeds the file’s contents intowc
. The result of this line count is stored in the variableline_count
. Finally, the script outputs the line count usingecho "The file $file has $line_count lines."
, displaying a message with the number of lines in “example.txt”.Using command substitution to count the lines in a file. - Area Calculation
#!/bin/bash length=10 width=5 area=$((length * width)) echo "The area of the rectangle is ${area} square units"
- Using let for Arithmetic
#!/bin/bash a=10 b=5 let sum=a+b echo "Sum: $sum"
This Bash script calculates the sum of two numbers using thelet
command, a built-in function for arithmetic operations. The script sets the variablesa
andb
to 10 and 5, respectively, witha=10
andb=5
. Thelet sum=a+b
command then performs the addition ofa
andb
, assigning the result (15) to the variablesum
. Finally, the script usesecho "Sum: $sum"
to print the sum, displaying “Sum: 15” on the console.Performing arithmetic with the let command.
Conclusion
Mastering arithmetic operations in Bash scripting opens up a world of possibilities for automating tasks and processing numerical data. Whether you’re performing simple calculations or complex operations involving floating-point numbers and scientific notation, Bash provides the tools and flexibility needed for effective scripting. By incorporating these examples into your scripts, you can enhance their functionality and efficiency.
Frequently Asked Questions: Bash Arithmetic Essentials
- What is Bash scripting? Bash scripting is a method to automate tasks in Unix-like operating systems using the Bash shell.
- How do I perform addition in Bash? Use
sum=$((a + b))
to add variablesa
andb
. - Can Bash handle floating-point arithmetic? Yes, by using external tools like
bc
orawk
. - What is the
expr
command used for? Theexpr
command performs basic arithmetic like addition and multiplication. - How to increment a variable in Bash? Use
((variable++))
for incrementing a variable’s value. - What does
$((expression))
do in Bash? This syntax performs arithmetic expansion with the given expression. - How to calculate the modulus in Bash? Use
modulus=$((a % b))
for calculating the modulus. - Is it possible to calculate power in Bash? Yes, use
power=$((base**exponent))
for power calculations. - How can I compare two numbers in Bash? Use conditional statements like
if ((a > b))
for comparison. - Can Bash perform loop operations with arithmetic? Yes, for loops can incorporate arithmetic operations, e.g.,
for ((i = 1; i <= 5; i++))
. - How to calculate the square root in Bash? Use
sqrt=$(echo "scale=2; sqrt($number)" | bc -l)
withbc
. - What is the role of the
let
command? Thelet
command is used for arithmetic assignments in Bash. - How to find the number of lines in a file? Use
line_count=$(wc -l < "$file")
to count lines in a file. - How to calculate area in Bash? Use
area=$((length * width))
for area calculation of a rectangle. - Can Bash script handle scientific notation? Yes, with the help of tools like
awk
, e.g.,awk 'BEGIN {print (1.23e2 + 3.45e3)}'
.