In Bash, single square brackets [ ] are used for evaluating conditional expressions, similar to [[ ]], but with some limitations. Here are the key points regarding their usage:
-
Basic Conditional Tests: You can use single brackets for simple tests, such as checking if a file exists or comparing strings.
if [ -f "file.txt" ]; then echo "File exists." fi -
String Comparison: You can compare strings using
=and!=, but you must quote variables to avoid issues with spaces.if [ "$var" = "value" ]; then echo "Match!" fi -
Integer Comparison: You can perform integer comparisons using
-eq,-ne,-lt,-le,-gt, and-ge.if [ "$num" -gt 10 ]; then echo "Num is greater than 10." fi -
Logical Operators: To combine conditions, you need to use
-a(and) and-o(or), which can be less readable.if [ "$var1" -gt 10 -a "$var2" -lt 20 ]; then echo "Both conditions are true." fi -
Word Splitting: Single brackets are subject to word splitting and pathname expansion, which can lead to unexpected behavior if not handled properly.
Overall, while single square brackets can be used for conditional expressions, [[ ]] is generally preferred for more complex conditions due to its enhanced features and safety.
