When should I use double brackets?

0191

You should use double brackets [[ ]] in Bash when:

  1. 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
  2. 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
  3. 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
  4. 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
  5. 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.

0 Comments

no data
Be the first to share your comment!