What is the purpose of the double square brackets '[[ ]] in Bash?

0579

In Bash, the double square brackets [[ ]] are used for conditional expressions. They provide a more powerful and flexible way to evaluate conditions compared to single square brackets [ ]. Here are some key features of [[ ]]:

  1. String Comparison: You can use == and != for string comparisons without needing to quote variables to prevent word splitting or globbing.

    if [[ "$var" == "value" ]]; then
        echo "Match!"
    fi
    
  2. Pattern Matching: The [[ ]] construct supports pattern matching with == and !=, allowing the use of wildcards.

    if [[ "$filename" == *.txt ]]; then
        echo "It's a text file."
    fi
    
  3. Logical Operators: You can use && and || for logical AND and OR operations directly within the condition.

    if [[ "$var1" == "value1" && "$var2" == "value2" ]]; then
        echo "Both conditions are true."
    fi
    
  4. No Need for Quoting: Unlike single brackets, you don't need to quote variables to prevent word splitting.

  5. Extended Test Features: [[ ]] supports additional features like regex matching with =~.

    if [[ "$var" =~ ^[0-9]+$ ]]; then
        echo "It's a number."
    fi
    

Overall, [[ ]] is preferred for conditional expressions in Bash scripts due to its enhanced capabilities and ease of use.

0 Comments

no data
Be the first to share your comment!