Bash Operators

Understanding operators for calculations and comparisons

🔢 What are Bash Operators?

Bash operators are symbols that perform operations on variables and values. They help you do math, compare values, and make logical decisions in your scripts.


#!/bin/bash
# Simple arithmetic operation
a=10
b=5
sum=$((a + b))
echo "Sum: $sum"
                                    

Output:

Sum: 15

Types of Operators

Arithmetic

Math operations

result=$((10 + 5))
⚖️

Comparison

Compare values

if [ $a -eq $b ]
🔗

Logical

Combine conditions

if [ $a -gt 5 ] && [ $b -lt 10 ]
📝

String

Work with text

if [ "$str1" = "$str2" ]

🔹 Arithmetic Operators

Arithmetic operators (+, -, *, /, %, etc.) perform mathematical calculations. In Bash, use the $(( )) construct for arithmetic expansion: result=$(( 5 + 3 )). This evaluates the expression and substitutes the result. Operators follow standard precedence. For exponentiation, use **. Note: division yields integers (truncated). For example, $(( 10 / 3 )) is 3. These operators enable counters, calculations, and numeric comparisons directly within scripts, forming the basis for dynamic numeric processing.

#!/bin/bash
a=20
b=10

# Addition
echo "Addition: $((a + b))"

# Subtraction
echo "Subtraction: $((a - b))"

# Multiplication
echo "Multiplication: $((a * b))"

# Division
echo "Division: $((a / b))"

# Modulus (remainder)
echo "Modulus: $((a % b))"

# Exponentiation
echo "Power: $((a ** 2))"

Output:

Addition: 30
Subtraction: 10
Multiplication: 200
Division: 2
Modulus: 0
Power: 400

🔹 Comparison Operators

Comparison operators (-eq, -ne, -lt, -gt, -le, -ge) compare numeric values. Used inside test brackets [ ] or [[ ]] for conditional statements. For example, [ "$a" -eq "$b" ] checks equality. It's crucial to use these for numbers, not string operators (=), to avoid incorrect evaluations. They are the workhorses of if statements and loop conditions involving counts, sizes, or other numeric data. Always ensure variables being compared contain integers to prevent syntax errors.

#!/bin/bash
num1=15
num2=10

# Equal to
if [ $num1 -eq $num2 ]; then
    echo "Equal"
else
    echo "Not equal"
fi

# Not equal to
[ $num1 -ne $num2 ] && echo "Numbers are different"

# Greater than
[ $num1 -gt $num2 ] && echo "$num1 is greater than $num2"

# Less than
[ $num1 -lt $num2 ] && echo "$num1 is less than $num2"

# Greater than or equal
[ $num1 -ge $num2 ] && echo "$num1 >= $num2"

# Less than or equal
[ $num1 -le $num2 ] && echo "$num1 <= $num2"

Output:

Not equal
Numbers are different
15 is greater than 10
15 >= 10

🔹 Logical Operators

Logical operators combine or invert test conditions: && (AND), || (OR), and ! (NOT). Inside [[ ]], they can link multiple expressions: [[ -f "$file" && -r "$file" ]]. The ! operator negates a condition: [[ ! -d "$dir" ]]. Outside test brackets, && and || control command execution based on exit codes. Understanding the difference between their use inside tests (for condition logic) and outside (for command chaining) is key to writing correct, efficient conditional scripts.

#!/bin/bash
age=25
score=85

# AND operator - both conditions must be true
if [ $age -ge 18 ] && [ $score -ge 80 ]; then
    echo "Eligible and qualified"
fi

# OR operator - at least one condition must be true
if [ $age -lt 18 ] || [ $score -lt 50 ]; then
    echo "Not eligible or not qualified"
else
    echo "Meets at least one requirement"
fi

# NOT operator - reverses the condition
if [ ! $age -lt 18 ]; then
    echo "Age is 18 or above"
fi

Output:

Eligible and qualified
Meets at least one requirement
Age is 18 or above

🔹 String Operators

String operators compare, check, and manipulate text data. Use = and != for equality/inequality tests: [ "$str1" = "$str2" ]. The -z operator tests for an empty string ([ -z "$var" ]), while -n tests for non-empty. Always quote variables in string tests to avoid word splitting errors. For pattern matching, use [[ "$var" == *pattern* ]] (with [[ ]]). These operators are essential for validating user input, parsing text, and controlling script flow based on content.

#!/bin/bash
str1="Hello"
str2="World"
str3=""

# String equality
if [ "$str1" = "$str2" ]; then
    echo "Strings are equal"
else
    echo "Strings are different"
fi

# String inequality
[ "$str1" != "$str2" ] && echo "$str1 is not equal to $str2"

# Check if string is empty
if [ -z "$str3" ]; then
    echo "str3 is empty"
fi

# Check if string is not empty
if [ -n "$str1" ]; then
    echo "str1 is not empty"
fi

Output:

Strings are different
Hello is not equal to World
str3 is empty
str1 is not empty

🔹 File Test Operators

File test operators check properties of files and directories. Common tests include -e (exists), -f (regular file), -d (directory), -r (readable), -w (writable), -x (executable), and -s (size > 0). Used in conditionals: if [ -f "/path/file" ]; then. They are indispensable for safe file operations—ensuring a file exists before reading, a directory exists before writing, or checking permissions. This prevents many common script errors and security issues related to filesystem interactions.

#!/bin/bash
file="test.txt"

# Check if file exists
if [ -e "$file" ]; then
    echo "File exists"
fi

# Check if it's a regular file
if [ -f "$file" ]; then
    echo "It's a regular file"
fi

# Check if it's a directory
if [ -d "$file" ]; then
    echo "It's a directory"
fi

# Check if file is readable
if [ -r "$file" ]; then
    echo "File is readable"
fi

# Check if file is writable
if [ -w "$file" ]; then
    echo "File is writable"
fi

# Check if file is executable
if [ -x "$file" ]; then
    echo "File is executable"
fi

Output:

File exists
It's a regular file
File is readable
File is writable

🧠 Test Your Knowledge

Which operator checks if two numbers are equal in Bash?