Arithmetic Operators in bash

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:

  1. Double Parentheses (()): This syntax lets you embed arithmetic expressions directly into your scripts.
  2. The let Command: A flexible way to assign results of arithmetic expressions to variables.

Syntax

# Double Parentheses
(( expression ))

# let Command
let variable=expression

Common Bash Arithmetic Operators

OperatorDescriptionExample
+Addition(( 5 + 3 ))
-Subtraction(( 10 - 4 ))
*Multiplication(( 6 * 2 ))
/Division(( 15 / 3 ))
%Modulus (remainder)(( 10 % 3 ))
**Exponentiation(( 2** 3 ))
+=Add and assignx += 5
-=Subtract and assigny -= 2
*=Multiply and assignz *= 4
/=Divide and assignw /= 3
++Incrementi++
--Decrementj--
Common Bash Arithmetic Operators

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:

  1. In the let command, 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.
  2. 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:

  1. Here, the ternary operator ?: evaluates a condition (x > y).
  2. If the condition is true, the value of x is assigned to the variable result.
  3. 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.