Skip to main content

How to Compare Numbers in Bash

• 2 min read
bash comparison operators conditional numeric arithmetic

Quick Answer: Compare Numbers in Bash

To compare numbers, use the -eq operator for equality: [ $a -eq 5 ]. For greater/less than, use -gt and -lt. Always quote variables to prevent errors: [ "$var" -gt 10 ]. The test operators are the standard, most portable method.

Quick Comparison: Number Comparison Methods

MethodSyntaxBest ForSpeed
Test operators[ $a -eq 5 ]Most casesFastest
Arithmetic (())(( a == 5 ))Bash onlyMedium
let commandlet result=a>5Legacy codeMedium
exprexpr $a = 5PortabilitySlower

Bottom line: Use test operators with -eq, -gt, -lt for all comparisons.


Numeric Comparison Operators

Bash provides several operators for comparing numbers. These are used in if statements, while loops, and other conditionals to make decisions based on numeric values.

Method 1: Using Test Operators (Standard)

Here are the primary numeric comparison operators in Bash:

OperatorMeaningExample
-eqEqual[ $a -eq 5 ]
-neNot equal[ $a -ne 5 ]
-ltLess than[ $a -lt 10 ]
-leLess than or equal[ $a -le 10 ]
-gtGreater than[ $a -gt 0 ]
-geGreater than or equal[ $a -ge 0 ]

These operators work with the [ ] test command or in arithmetic expressions with (( )).

Using the Test Command [ ]

The traditional way to compare numbers uses square brackets:

#!/bin/bash

AGE=25

# Check if age equals 25
if [ $AGE -eq 25 ]; then
  echo "You are 25 years old"
fi

# Check if age is greater than 18
if [ $AGE -gt 18 ]; then
  echo "You are an adult"
fi

# Check if age is less than 65
if [ $AGE -lt 65 ]; then
  echo "You are working age"
fi

Using Arithmetic Expressions (( ))

Modern Bash prefers the (( )) syntax, which is cleaner and uses familiar operators like >, <, ==:

#!/bin/bash

AGE=25

# Using (( )) - feels more like other programming languages
if (( AGE == 25 )); then
  echo "You are 25 years old"
fi

if (( AGE > 18 )); then
  echo "You are an adult"
fi

if (( AGE < 65 )); then
  echo "You are working age"
fi

# Operators in (( ))
# ==, !=, <, <=, >, >=

Practical Example: Age Verification

Here’s a script that validates age input and provides different messages:

#!/bin/bash

read -p "Enter your age: " age

# Check if input is a number
if ! [[ "$age" =~ ^[0-9]+$ ]]; then
  echo "ERROR: Please enter a valid number"
  exit 1
fi

# Categorize by age
if (( age < 13 )); then
  echo "You are a child"
elif (( age < 18 )); then
  echo "You are a teenager"
elif (( age < 65 )); then
  echo "You are an adult"
else
  echo "You are a senior"
fi

# Check specific ranges
if (( age >= 18 && age <= 21 )); then
  echo "You are in the young adult category"
fi

Comparing Multiple Conditions

Combine numeric comparisons with && and ||:

#!/bin/bash

TEMPERATURE=$1
HUMIDITY=$2

# Check if temperature is in safe range AND humidity is acceptable
if (( TEMPERATURE > 0 && TEMPERATURE < 40 )) && (( HUMIDITY < 80 )); then
  echo "Environment is safe"
else
  echo "Environment out of safe range"
fi

# Check if either condition indicates danger
if (( TEMPERATURE > 100 || HUMIDITY > 95 )); then
  echo "WARNING: Dangerous conditions detected!"
  exit 1
fi

Real-World Example: Disk Space Monitor

#!/bin/bash

# Get disk usage percentage for root filesystem
DISK_USAGE=$(df / | tail -1 | awk '{print $5}' | sed 's/%//')

echo "Disk usage: ${DISK_USAGE}%"

# Warn if disk is getting full
if (( DISK_USAGE > 90 )); then
  echo "CRITICAL: Disk almost full!"
  exit 1
elif (( DISK_USAGE > 75 )); then
  echo "WARNING: Disk usage is high"
  exit 0
elif (( DISK_USAGE > 50 )); then
  echo "NOTICE: Disk usage is moderate"
  exit 0
else
  echo "OK: Plenty of disk space"
  exit 0
fi

Incrementing and Decrementing

Common numeric operations inside (( )):

#!/bin/bash

# Increment
count=0
((count++))  # count is now 1
((count += 5))  # count is now 6

# Decrement
((count--))  # count is now 5
((count -= 2))  # count is now 3

# Multiplication
((result = count * 10))  # result is now 30

# Division
((result = result / 2))  # result is now 15

echo "Final count: $count, result: $result"

Important Notes

Always quote variables in comparisons:

# CORRECT
if [ "$age" -gt 18 ]; then

# WRONG - will fail if $age is empty
if [ $age -gt 18 ]; then

The difference between [ ] and (( )):

# [ ] uses -eq, -gt, -lt operators
if [ 5 -eq 5 ]; then
  echo "Equal"
fi

# (( )) uses ==, >, < operators
if (( 5 == 5 )); then
  echo "Equal"
fi

Quick Reference

# Equal
[ $a -eq $b ]    # [ ] syntax
(( a == b ))     # (( )) syntax

# Not equal
[ $a -ne $b ]    # [ ] syntax
(( a != b ))     # (( )) syntax

# Less than
[ $a -lt $b ]    # [ ] syntax
(( a < b ))      # (( )) syntax

# Greater than
[ $a -gt $b ]    # [ ] syntax
(( a > b ))      # (( )) syntax

# Less than or equal
[ $a -le $b ]    # [ ] syntax
(( a <= b ))     # (( )) syntax

# Greater than or equal
[ $a -ge $b ]    # [ ] syntax
(( a >= b ))     # (( )) syntax

Summary

Numeric comparisons are essential for making decisions in scripts. Use (( )) in modern Bash for cleaner syntax, or [ ] with -eq, -lt, -gt operators for compatibility with older shells. Always quote variables and remember that these operators only work with integers, not floating-point numbers.