Bash Arithmetic OperatorsIn 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 BashThere 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 ParenthesesDouble 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 $. Syntax 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) : Method 1 Method 2 Method 3 Method 4 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: Bash Script Output Let ConstructionLet is a builtin command of Bash that allows us to perform arithmetic operations. It follows the basic format: Syntax An example is given below explaining how to use let command in a Bash script: Bash script Output BackticksIn bash scripting, an arithmetic expansion can also be performed using backticks and expr (known as allpurpose 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'. Syntax An example is given below explaining how to use backticks and expr in a Bash script: Bash Script Program Output ConclusionIn this topic, we discussed how to use arithmetic operators to perform arithmetic operations.
Next TopicBash If Statement
