Have you ever performed any arithmetic calculations in Bash? If you’re new to Bash scripting, you might encounter difficulties when it requires to evaluate an arithmetic expression. In this article, I’ll demonstrate the syntax and guide you on where and how to write arithmetic expressions to ensure accurate calculation. Along with this arithmetic expansion for calculation, I will show you a few commands that can effectively perform arithmetic calculation in Bash.
Syntax of Arithmetic Expansion
The syntax of arithmetic expansion in Bash is $((...))
. Inside the double parentheses, you can put mathematical expressions, variables, and operators. The shell will evaluate the expression and replace the $((…)) construct with the result of the calculation. Let’s calculate the sum of 4 and 5 in the terminal.
echo $((4 + 5))
The image shows the addition of 4 and 5 inside the $((…)). Then it prints the evaluated result 9 using the echo command.
3 Practical Applications of Arithmetic Expansion in Bash
There are many applications of arithmetic expansion in Bash scripting. In this article, I’d like to highlight three fundamental use cases of arithmetic expansion, which encompass scenarios such as multiplication and bitwise operations and others.
1. Multiplication of Two Integer Numbers in Bash
In this demonstration, I want to show how to multiply two numbers in Bash. In the case of arithmetic expansion, the numbers to be multiplied should be integer type. Floating point numbers can’t be multiplied in this way.
To perform the multiplication of two integer numbers using arithmetic expansion, check the bash script:
#!/bin/bash
# Prompt the user to enter the first number
read -p "Enter the first integer: " num1
# Prompt the user to enter the second number
read -p "Enter the second integer: " num2
# Perform the multiplication
result=$((num1 * num2))
# Display the result
echo "The product of $num1 and $num2 is $result"
The script begins by prompting the user to input two integer values. It uses the read
command to capture these inputs.
After collecting the user’s input, it performs the multiplication of these two integer values using the arithmetic *
operator. Finally, the script displays a message indicating the product of the two input numbers utilizing the echo
command.
Once executed the program takes two integer inputs from the user and calculates their product. In the above execution, entering integers 4 and 5 in the program returns 20 as their product.
Bash Arithmetic Operators
Apart from the multiplication operator, there are other arithmetic operators. The below list contains all the arithmetic operators for basic calculation:
Operator | Description | Example |
---|---|---|
Addition (+) | Adds two numbers together. | $((5 + 3)) is 8 |
Subtraction (-) | Subtracts the right operand from the left operand. | $((10 – 3)) is 7 |
Multiplication (*) | Multiplies two numbers. | $((4 * 6)) is 24 |
Division (/) | Divides the left operand by the right operand. | $((10 / 3)) is 3 |
Modulus (%) | Computes the remainder when the left operand is divided by the right operand. | $((10 % 3)) is 1 |
2. Bash Script for Checking Odd or Even Number
You can easily check even or odd numbers in Bash using the remainder or modulus %
operator. The following script shows how to determine whether a number is odd or even using arithmetic expansion:
#!/bin/bash
# Bash script to check if a number is even or odd
read -p "Enter the number: " number
check=$((number % 2))
if [ $check -eq 0 ]; then
echo "The number is even."
else
echo "The number is odd."
fi
This Bash script allows the user to input a number, which is stored in the number variable using the read
command. It then calculates the remainder when the number is divided by 2 using the %
operator. If the remainder is 0, the script prints “The number is even.” Conversely, if the remainder is not 0, it prints “The number is odd.”
It is evident that the remainder can be easily calculated by the % operator. But what happens if there are multiple operators in a single calculation? Let’s talk about the precedence rule in Bash.
Precedence Rules in Bash
Bash follows standard arithmetic operator precedence rule. One can use parentheses to explicitly specify the order of operations. But if not specified, it performs Exponents, Multiplication, Division, Addition and Subtraction consecutively.
echo $((2 ** 4 / 2))
In this calculation, arithmetic expansion first computes 2^4, which equals 16. Then, it divides the result by 2, yielding a final answer of 8.
Can you imagine what happens if you put one arithmetic expansion inside another? Let’s explore the nested feature of arithmetic expansion.
Nested Arithmetic Expansion
The arithmetic expansion also works in a nested fashion. It means you can expand an arithmetic calculation inside another calculation. Let’s see an example of it:
echo $((2 * $(( 4 + 6))))
As you can see, in the above code $(( 4 + 6)) expands inside another arithmetic expansion.
3. Bitwise “AND” Operation in Bash
Bash can handle bitwise calculation using arithmetic expansion. In this application, I want to show bitwise AND operation with &
operator. Now, to perform bitwise AND operation using arithmetic expansion, check this bash script:
#!/bin/bash
# Define two decimal numbers
num1=10
num2=6
# Perform bitwise AND operation
result=$((num1 & num2))
# Print the result
echo "Result of $num1 & $num2 is $result"
The above script defines two decimal numbers, num1 and num2, as 10 and 6, respectively. It then performs a bitwise AND operation between these numbers using the &
operator and stores the result in a variable. The script then displays the result of bitwise AND operation using the echo
command.
In this bitwise AND operation, the binary representations of 10 and 6 are 1010 and 0110 respectively. Their bitwise AND results in 0010, which is 2 in decimal.
Floating Point Arithmetic in Bash
The arithmetic expansion in Bash is originally designed for working with integers. It can’t perform arithmetic calculations of floating point numbers. Fortunately, there are other commands like the bc command that can perform calculations with floating point numbers.
To add two floating point numbers using the bc
command, follow the bash script:
#!/bin/bash
# Define floating-point numbers
num1=3.14
num2=2.5
# Perform floating-point addition using bc command
result=$(echo "$num1 + $num2" | bc -l)
# Print the result
echo "Sum of $num1 + $num2 is $result"
This Bash script aims to add two floating-point numbers, num1 and num2, with values 3.14 and 2.5, respectively. The echo
command is used to construct the expression for addition. Then it utilizes the bc
command and piped the expression into bc -l
. Here, -l
option specifies the standard math library.
The program computes the addition of 3.14 and 2.5. Result 5.64 is displayed in the terminal.
Alternatives of Arithmetic Expansion in Bash
Arithmetic expansion is designed to perform integer arithmetic in Bash. However, there are many other alternatives to it. As I already discussed the bc command, there are few other commands such as the let command, expr command and awk command that can be employed to perform arithmetic calculations in place of arithmetic expansion. Let’s see some examples of each of these commands.
1. Utilizing the “expr” Command
To perform arithmetic calculation using the expr
command, write the expression after the word expr. But never forget to enclose the whole expression with a dollar sign. The whole syntax should be something like this- $(expr expression)
Here is a bash script to perform subtraction operation using expr
command:
#!/bin/bash
# Prompt the user to enter the first number
read -p "Enter the first number: " num1
# Prompt the user to enter the second number
read -p "Enter the second number: " num2
sub_result=$(expr $num1 - $num2)
echo "Subtraction Result: $sub_result"
The script uses the read
command with the -p
option to take input in the num1 and num2 variables, respectively. Subsequently, it utilizes the expr
command to perform subtraction between num1 and num2. The result is stored in the sub_result
variable. Finally, it employs the echo
command to display the subtraction result.
The image shows that the expr command successfully subtracts 5 from 10.
2. Employing the “awk” Command
The awk
command is mainly used for text processing and data manipulation. However, it can be used for arithmetic calculation as well. In this demonstration, I will show you how to add two numbers using the awk command. Let’s see the bash script for this:
#!/bin/bash
# Prompt the user to enter the first number
read -p "Enter the first number: " num1
# Prompt the user to enter the second number
read -p "Enter the second number: " num2
# Use awk to perform the addition and store the result in the 'result' variable
result=$(awk -v n1="$num1" -v n2="$num2" 'BEGIN {print n1 + n2}')
# Print the result
echo "Result: $result"
This Bash script prompts the user to input two numbers, num1 and num2 using the read command. It then employs the awk
command with the -v
option to pass these numbers as variables n1 and n2. Within an awk BEGIN block, it calculates the sum of n1 and n2 and displays the result using the echo
command.
The image shows that the program calculates the summation of 10 and 15 and displays the result.
3. Using the “let” Command
The let command is another very good alternative to arithmetic expansion. It evaluates arithmetic expressions without any syntax complexity. Let’s increment a variable by one using the let
command. Here’s how:
#!/bin/bash
read -p "Enter the number: " num
let "num=num+1"
echo "Result: $num"
This Bash script prompts the user to enter a number, which is stored in the num variable. Then it utilizes the let
command to increment the value of num by 1. Finally, it echoes the incremented value of num using the echo
command.
As the image shows, the let command adds 1 with the user input 5. After addition, it shows the result 6 in the terminal.
How Arithmetic Evaluation Differs from Arithmetic Expansion
Arithmetic evaluation differs from arithmetic expansion in Bash. $[ expression ]
or (( expression ))
syntax can evaluate the expression inside it. However, these constructs don’t store the result of evaluation, rather it compares the calculated value with a predefined threshold. This is particularly useful for control structures in Bash.
Look at the script below to see how arithmetic evaluation is used in control structures of the Bash script:
#!/bin/bash
# Bash script to check if a number is even or odd
read -p "Enter the number:" number
if ((number % 2 == 0)); then
echo "The number is even."
else
echo "The number is odd."
fi
This Bash script allows the user to input a number, which is stored in the number variable using the read command. It then calculates the remainder when the number is divided by 2 using the %
operator. If the remainder is 0, the script prints “The number is even.” Conversely, if the remainder is not 0, it prints “The number is odd.”
The program works perfectly as it determines 5 as an odd number. Within the if structure the program divides the number by two and compares it with zero using ((number % 2 == 0)) construction. This certainly differs from arithmetic expansion that have double parenthesis followed by a dollar sign.
Conclusion
In conclusion, arithmetic expansion is essential for any kind of arithmetic calculation in Bash. I believe that after reading this article, you have a clear understanding of arithmetic expansion in Bash scripting. Furthermore, I have attempted to provide you with information about alternative commands for arithmetic calculations in Bash. Hope you have enjoyed reading the text.
People Also Ask
What is arithmetic expansion in Bash?
Arithmetic expansion is a feature in bash that uses double parentheses to perform mathematical calculations directly in the bash shell. The basic syntax of arithmetic expansion is: $((...))
.
How to perform arithmetic expansion in Bash?
To perform arithmetic expansion in bash, you can use this syntax: $((...))
. Inside the double parentheses, you can perform different arithmetic operations like addition, subtraction, multiplication, and so on.
How to multiply two number variables in Bash?
To multiply two number variables, you can use arithmetic expansion in Bash. Follow this syntax to multiply variables number1 and number2: multiplication=$((number1 * number2))
.
Are there any alternatives to arithmetic expansion in Bash?
Yes, there are some alternatives to arithmetic expansion in bash. You can use bc
, expr
, let
, and awk
command instead of using arithmetic expansion to perform arithmetic calculations in bash.
Why arithmetic expansion doesn’t work inside quote?
Arithmetic expansion works perfectly within double quotes. On the other hand, inside single quote everything is treated as literal including a dollar sign used for arithmetic expansion.
What arithmetic expansion expands to if nothing in the expression?
If there is nothing in the arithmetic expansion say- echo $(())
then it expands to zero.
Why it shows invalid arithmetic operator instead of arithmetic expansion in Bash?
It may be due to the floating point arithmetic. Regular arithmetic expansion can handle the integer arithmetic only. To work with floating point numbers use the bc
command. This may resolve the issue of an invalid arithmetic operator.
Related Articles
- How to Use Brace Expansion in Bash Scripting [3 Cases]
- How to Use Tilde Expansion in Bash [4 Practical Cases]
- Parameter Expansion in Bash [3 Main Types]
- An Exhaustive Guide to Bash History Expansion
- What is Array Expansion in Bash [4 Useful Applications]
- Glob Expansion in Bash
<< Go Back to An Overview of Shell Expansion in Bash | Bash Scripting Tutorial
FUNDAMENTALS A Complete Guide for Beginners