Bash Number Tests
Number tests compare two whole numbers inside square brackets. Each operator checks one kind of relationship.
Greater Than
The operator -gt means greater than. Seven is greater than five, so the line prints.
score=7
if [ "$score" -gt 5 ]; then
echo "7 is greater than 5"
fiEqual and Not Equal
The operator -eq means equal to. The operator -ne means not equal to.
count=4
if [ "$count" -eq 4 ]; then
echo "4 equals 4"
fi
if [ "$count" -ne 9 ]; then
echo "4 is not equal to 9"
fiLess Than and a False Test
The operators -lt and -le cover smaller numbers. The last test fails, so its else branch prints.
temp=3
if [ "$temp" -lt 5 ]; then
echo "3 is less than 5"
fi
if [ "$temp" -le 3 ]; then
echo "3 is less than or equal to 3"
fi
if [ "$temp" -gt 10 ]; then
echo "3 is greater than 10"
else
echo "3 is not greater than 10"
fiExample
marks=80
if [ "$marks" -ge 60 ]; then
echo "80 meets the pass mark of 60"
fi
if [ "$marks" -ge 90 ]; then
echo "80 is in the top band"
else
echo "80 is below the top band of 90"
fiKey points
- The operator -eq checks that two numbers are equal.
- The operator -ne checks that two numbers differ.
- The operator -lt checks for less than.
- The operator -le allows a number to be equal too.
- The operator -gt checks for greater than.
- The operator -ge allows a number to be equal too.
In this example, -ge tests greater than or equal to. The first test passes, and the second test fails into the else branch.
Try it Yourself
Edit the code, then press Run.
Running is simulated
Exercise
Which operator means less than or equal to?