String Comparisons in Bash
String comparisons in Bash allow you to evaluate relationships between strings, such as equality, inequality, and pattern matching. These comparisons are often used in conditional statements like if
, while
, and case
.
String Comparison Operators
Operator | Description |
---|---|
= | Strings are equal |
== | Strings are equal (used in [[ ]] only) |
!= | Strings are not equal |
< | String1 is less than String2 (ASCII order) |
> | String1 is greater than String2 (ASCII order) |
-z | String is empty |
-n | String is not empty |
Basic Syntax
Examples of String Comparisons
1. Check String Equality
2. Check String Inequality
Empty and Non-Empty Strings
3. Check If a String is Empty
4. Check If a String is Non-Empty
Lexicographical Comparisons
5. Compare Strings in ASCII Order
Using [[ ]]
for Advanced Comparisons
The [[ ]]
construct is more powerful than [ ]
and allows for advanced pattern matching:
6. Pattern Matching
7. Case-Insensitive Matching
(The ${word,,}
syntax converts the string to lowercase.)
Regular Expression Matching
Bash 3.0+ supports regular expressions in [[ ]]
with the =~
operator:
8. Regex Example
Combine String Comparisons with Logical Operators
9. Logical AND
10. Logical OR
Common Mistakes and Tips
Quote Variables: Always quote variables to avoid errors with empty strings or special characters.
Use
[[ ]]
for Complex Patterns: For string comparisons involving wildcards or regex, use[[ ]]
instead of[ ]
.ASCII Order: The
<
and>
operators compare strings lexicographically (based on ASCII values). Ensure you understand the case sensitivity of comparisons.
Conclusion
String comparisons in Bash are essential for decision-making in scripts. By mastering the operators and constructs, you can handle a wide range of tasks, from basic equality checks to complex pattern matching.
Let me know if you’d like additional examples or further refinements!