Bash Arithmetic Operations
You can perform arithmetic operations on numeric values in bash scripts. You can find many options to perform arithmetic operations on bash shell but below example will provide you simplest way.
Syntax:
((expression)) ((var1+var2)) ((var1-var2)) ((var1*var2)) ((var1/var2))
Bash Arithmetic Operations Example:
For example, take an input of two numeric values and perform all 5 basic arithmetic operations like below:
1 2 3 4 5 6 7 8 9 10 | #!/bin/bash read -p "Enter numeric value: " n1 read -p "Enter numeric value: " n2 echo "Addition of $n1 + $n2 is = " $((n1+n2)) echo "Subtraction of $n1 - $n2 is = " $((n1-n2)) echo "Division of $n1 / $n2 is = " $((n1/n2)) echo "Multiplication of $n1 * $n2 is = " $((n1*n2)) echo "Modulus of $n1 % $n2 is = " $((n1%n2)) |
Increment and Decrement Operator:
Bash also used incremnt (++) and decrement (–) operators. Both uses in two types pre-increment/post-increment and pre-decrement/post-decrement.
1 2 3 4 5 6 7 | ## Post-increment example $ var=10 $ echo $((var++)) ## First print 10 then increase value by 1 ## Pre-increment example $ var=10 $ echo $((++var)) ## First increase value by 1 then print 11 |
Similarly, try pre-decrement and post-decrement operators in the bash shell.
1 2 3 4 5 6 7 | ## Post-decrement example $ var=10 $ echo $((var--)) ## First print 10 then decrease value by 1 ## Pre-decrement example $ var=10 $ echo $((--var)) ## First decrease value by 1 then print 9 |