Junior — Middle
What is the difference between using single brackets [] and double brackets [[]] in bash?
sobes.tech AI
Answer from AI
In bash, single brackets [] and double brackets [[]] are used for conditions, but there are important differences between them:
-
[] is the standard POSIX-compatible test, which runs the test command. It is limited in syntax and requires careful escaping and quoting.
-
[[]] is an extension of bash (and some other shells), which supports more powerful syntax:
- Allows the use of logical operators &&, || inside the conditional expression.
- Supports regular expressions with the operator =~.
- Does not require strict variable escaping, fewer issues with spaces.
Example:
if [ "$var" = "value" ]; then
echo "Regular test"
fi
if [[ $var == v* ]]; then
echo "Using pattern with [[ ]]"
fi
In summary, [[]] is more flexible and convenient for writing complex conditions in bash, but it is not POSIX-compatible.