Arithmetic Operators in bash
2024-06-18
Bash, the Swiss army knife of scripting languages, offers a rich set of arithmetic operators for performing calculations directly within your scripts. Let’s delve into how these operators can streamline your number-crunching tasks.
Harnessing the Power of Calculations
Bash makes arithmetic operations a breeze using two primary methods:
- Double Parentheses
(()): This syntax lets you embed arithmetic expressions directly into your scripts. - The
letCommand: A flexible way to assign results of arithmetic expressions to variables.
Syntax
# Double Parentheses
(( expression ))
# let Command
let variable=expression
Common Bash Arithmetic Operators
Operator
Description
Example
Addition
(( 5 + 3 ))
–
Subtraction
(( 10 – 4 ))
*
Multiplication
(( 6 * 2 ))
/
Division
(( 15 / 3 ))
%
Modulus (remainder)
(( 10 % 3 ))
**
Exponentiation
(( 2** 3 ))
Add and assign
Subtract and assign
Multiply and assign
Divide and assign
++
Increment
i++
—
Decrement
j–
Examples
Example 1: Basic Arithmetic
(( result = 2 + 3 * 4 ))
echo $result # Output: 14
Example 2: Increment and Decrement
count=5
(( count++ ))
echo $count # Output: 6
(( count-- ))
echo $count # Output: 5
Example 3: Bitwise XOR (Exclusive OR)
n=13 # Binary: 1101
result=$(( n ^ 4 )) # 4 in binary is 0100
echo $result # Output: 9 (Binary: 1001)
Explanation:
- In the
letcommand, n is assigned the value of 2 to the power of 3 (2 * 2 * 2) which equals 8, plus 5, for a total of 13. - Then, using bitwise XOR (^) with 4 (binary 0100), only the bits in positions 3 and 0 remain ‘on’ in the result, giving us 1001 in binary which equals 9.
Example 4: Conditional Expression
x=10
y=5
result=$(( (x > y) ? x : y )) # Ternary operator
echo $result # Output: 10
Explanation:
- If the condition is true, the value of x is assigned to the variable result.
- If the condition is false, the value of y is assigned to result.
Why Use Arithmetic Operators in Bash?
- Efficiency: Perform calculations directly within your scripts, avoiding the need for external tools.
- Flexibility: Combine arithmetic with other Bash features for powerful scripting logic.
- Conciseness: Write cleaner, more compact code.
Feel free to experiment with these operators and discover how they can elevate your Bash scripting capabilities.