You should use double brackets [[ ]] in Bash when:
-
String Comparison: You want to compare strings without worrying about quoting variables. Double brackets allow you to use
==and!=without needing to quote the variables.if [[ $var == "value" ]]; then echo "Match!" fi -
Pattern Matching: You need to perform pattern matching with wildcards. Double brackets support pattern matching directly.
if [[ $filename == *.txt ]]; then echo "It's a text file." fi -
Logical Operators: You want to combine multiple conditions using
&&(and) and||(or) for better readability.if [[ $var -gt 10 && $var -lt 20 ]]; then echo "Var is between 10 and 20." fi -
Avoiding Word Splitting: You want to prevent word splitting and pathname expansion, which can lead to errors in your conditions.
if [[ $var == "some value" ]]; then echo "Value matches." fi -
Safer Syntax: You prefer a more robust syntax that reduces the risk of syntax errors and improves code clarity.
In summary, use double brackets [[ ]] for more complex conditions, better readability, and to take advantage of additional features that single brackets [ ] do not provide.
