Bash Shell Number Comparison

In the Bash shell, you can perform numerical comparisons to determine if one number is equal to, greater than, or less than another. You can use the following comparison operators for this purpose:

  • -eq: Equal to
  • -ne: Not equal to
  • -lt: Less than
  • -le: Less than or equal to
  • -gt: Greater than
  • -ge: Greater than or equal to

Here are some examples of using these comparison operators in the Bash shell:

# Check if two numbers are equal
if [ $num1 -eq $num2 ]; then
echo "$num1 is equal to $num2"
fi

# Check if one number is greater than another
if [ $num1 -gt $num2 ]; then
echo "$num1 is greater than $num2"
fi

# Check if one number is less than another
if [ $num1 -lt $num2 ]; then
echo "$num1 is less than $num2"
fi

# Check if one number is greater than or equal to another
if [ $num1 -ge $num2 ]; then
echo "$num1 is greater than or equal to $num2"
fi

# Check if one number is less than or equal to another
if [ $num1 -le $num2 ]; then
echo "$num1 is less than or equal to $num2"
fi

Note: When comparing numbers in the Bash shell, make sure to use double square brackets ([[ ]]) instead of single square brackets ([ ]). This ensures that the comparison is treated as a numerical comparison rather than a string comparison.

Leave a Comment