Bash Arithmetic Operators
In this topic, we will understand how to use arithmetic operators in Bash.
Depending on what type of result we want through our scripts, we may need to apply arithmetic operators at some point. Like variables, they are reasonably easy to apply. In the bash script, we can perform arithmetic operations on numeric values to get the desired result.
There are 11 arithmetic operators which are supported by Bash Shell.
Look at the following table demonstrating the syntax, description and examples for each of the arithmetic operators:
Performing Arithmetic Operations in Bash
There are many options to perform arithmetic operations on the bash shell. Some of the options are given below that we can adopt to perform arithmetic operations:
Double parentheses is the easiest mechanism to perform basic arithmetic operations in the Bash shell. We can use this method by using double brackets with or without a leading $.
We can apply four different ways to achieve the required objectives. Look at the methods given below to understand how the double parentheses mechanism can be used (Assuming that we want to add the numbers 10 and 3) :
All of these methods will provide the same output as:
Sum = 13
Following is an example demonstrating the use of double parentheses for arithmetic operations in a Bash shell script:
Let is a built-in command of Bash that allows us to perform arithmetic operations. It follows the basic format:
An example is given below explaining how to use let command in a Bash script:
In bash scripting, an arithmetic expansion can also be performed using backticks and expr (known as all-purpose expression evaluator). The `expr` is similar to 'let,' but it does not save the result to a variable. It directly prints the result. Unlike let, we don't need to enclose the expression within the quotes. We are required to use spaces between the items of the expression. It is important to note that we should use 'expr` within command substitution to save the output to a variable.
We can also use `expr` without 'backticks'.
An example is given below explaining how to use backticks and expr in a Bash script:
Bash Script Program
In this topic, we discussed how to use arithmetic operators to perform arithmetic operations.