Lesson 9: Bash Maths Operations (Bash Arithmetic) Examples
Welcome to Lesson 9: Bash Maths Operations (Bash Arithmetic). In this lesson, we’ll dive into Bash arithmetic and explore how to perform basic mathematical operations in your scripts. Whether you need to calculate values, manipulate numbers, or automate tasks involving numerical data, mastering Bash maths operations is an essential skill for any Bash scripter. You’ll learn how to perform addition, subtraction, multiplication, division, and modulus operations, as well as work with variables for more dynamic calculations. With practical examples, you’ll gain hands-on experience that will empower you to automate complex tasks involving numbers with ease. Let’s get started with Bash arithmetic!
Introduction
Bash handles maths operations differently from many other programming languages.
In this article, you will see some common numerical operations.
More information about floating-point arithmetic you can find at the link.
Arithmetic Operations
In Bash, you can perform arithmetic operations using various methods, including the (( ))
syntax, which is specifically designed for arithmetic. Here are some of the basic arithmetic operations in Bash:
num1=5
num2=3
sum=$((num1 + num2))
echo $sum # Output: 8
Increment and Decrement
Increment and decrement operations are frequently used to increase or decrease a variable’s value. These operations are especially useful in loops, where you need to track the number of iterations or adjust a variable’s value dynamically as the script executes. By leveraging these operations, you can efficiently control loops or perform repetitive tasks in Bash scripts.
num=5
((num++))
echo $num # Output: 6
((num--))
echo $num # Output: 5
Comparison Operations
Comparison operations in Bash allow you to compare two values and assess their relationship—whether one value is greater than, less than, or equal to another. These operations play a crucial role in controlling the flow of a script, particularly when used in conditional statements like if
and while
. By performing comparisons, you can make decisions based on the outcomes, enabling dynamic and flexible script execution.
num1=5
num2=3
if [ $num1 -gt $num2 ]; then
echo "$num1 is greater than $num2"
else
echo "$num1 is not greater than $num2"
fi
Floating Point Arithmetic Operations
num1=5.5
num2=3.2
result=$(echo "$num1 + $num2" | bc)
echo $result # Output: 8.7
Practical Examples
In this section, we’ll dive into practical examples that showcase the power of Bash for performing arithmetic operations and processing text. By applying Bash to real-world scenarios, you can significantly enhance your scripts’ capabilities. Let’s explore these examples:
Counting Words in a String
str="Hello World from Bash"
word_count=$(echo $str | wc -w)
echo "Word count: $word_count" # Output: Word count: 4
Calculating the Sum of Numbers in a File
sum=0
while read num; do
sum=$((sum + num))
done < numbers.txt
echo "Sum: $sum"