Integer comparisons help you check if numbers are equal, different, or which one is bigger. This is useful to make decisions in scripts.
0
0
Integer comparisons (-eq, -ne, -gt, -lt, -ge, -le) in Bash Scripting
Introduction
Check if a user entered the correct number in a script.
Compare two file sizes to decide which one to keep.
Run a command only if a number is greater than a limit.
Loop until a number reaches a certain value.
Decide what message to show based on a score.
Syntax
Bash Scripting
[ number1 -operator number2 ]
Use spaces around brackets and operators.
Operators: -eq (equal), -ne (not equal), -gt (greater than), -lt (less than), -ge (greater or equal), -le (less or equal).
Examples
Checks if 5 is equal to 5 (true).
Bash Scripting
[ 5 -eq 5 ]
Checks if 3 is not equal to 4 (true).
Bash Scripting
[ 3 -ne 4 ]
Checks if 7 is greater than 2 (true).
Bash Scripting
[ 7 -gt 2 ]
Checks if 1 is less than or equal to 1 (true).
Bash Scripting
[ 1 -le 1 ]
Sample Program
This script compares two numbers and prints if the first is equal, less, or greater than the second.
Bash Scripting
#!/bin/bash num1=10 num2=20 if [ "$num1" -eq "$num2" ]; then echo "$num1 is equal to $num2" elif [ "$num1" -lt "$num2" ]; then echo "$num1 is less than $num2" else echo "$num1 is greater than $num2" fi
OutputSuccess
Important Notes
Always put spaces around the brackets and operators, or the comparison will fail.
Use integer comparisons only for whole numbers, not decimals.
For string comparisons, use different operators like = or !=.
Summary
Integer comparisons let you check relationships between numbers in bash scripts.
Use -eq, -ne, -gt, -lt, -ge, and -le inside [ ] with spaces.
They help your script make decisions based on numbers.