Numeric Comparisons in Bash
Numeric comparisons in Bash allow you to evaluate relationships between numbers, such as equality, inequality, and order. These comparisons are essential for scripting tasks like loops, conditionals, and arithmetic operations.
Numeric Comparison Operators
Operator | Description |
---|---|
-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 |
Basic Syntax
Examples of Numeric Comparisons
1. Check Equality
2. Check Inequality
Greater Than and Less Than
3. Compare Two Numbers
4. Check for Less Than
Combining Numeric Comparisons
You can combine conditions using logical operators like &&
(AND) and ||
(OR).
5. Logical AND
6. Logical OR
Using Double Parentheses for Numeric Comparisons
The the (( ))
syntax is a more concise and flexible way to perform numeric comparisons. It eliminates the need for -eq
, -ne
, etc.
7. Basic Comparison with (( ))
8. Combining Conditions in (( ))
Example: Validating User Input
9. Check if Input is Positive
10. Check If Number is Even or Odd
Error Handling in Numeric Comparisons
Ensure Variables Contain Numbers: If a variable contains non-numeric data, comparisons will fail. Use regex or arithmetic expansion to validate input:
Avoid Uninitialized Variables: Always initialize variables before using them in numeric comparisons:
Common Mistakes and Tips
Do Not Use String Comparisons for Numbers: Numeric comparisons must use
-eq
,-lt
, etc., or(( ))
.Quote Variables in Test Commands: Quote variables in
[ ]
to avoid errors with empty or special values:Avoid Spaces Around Assignment: Ensure there are no spaces around
=
in variable assignments:
Conclusion
Numeric comparisons are a fundamental part of Bash scripting, enabling conditional logic for a wide range of tasks. By mastering the operators and syntax, you can write robust and efficient scripts.
Let me know if you need additional examples or further refinements!