In Shell scripts, [] and [[]] are different syntax structures used for conditional testing. They have some differences, mainly reflected in support of string processing and expressions.
Single brackets ([ ]):
[] Also known as the test command, it supports basic conditional testing. as follows:
- When comparing strings, you usually use = or !=, for example [ "$var" = "value" ].
- When comparing numerical values, use operators such as -eq, -ne, -lt, -le, -gt, -ge, etc., such as [ $num -eq 10 ].
- Variables and strings in [] are usually enclosed in quotes to prevent syntax errors due to empty variables.
Double brackets ([[ ]]):
[[]] is an extension of Bash, providing more functions, including advanced string comparison, regular expression matching, etc.
- When comparing strings, you can use == or !=, such as [[ "$var" == "value" ]].
- When comparing numerical values, operators such as ==, !=, <, <=, >, >= are supported, such as [[ $num == 10 ]].
- There is no need to use quotes for variables and strings, although quotes are still safe.
for example:
#!/bin/bash var="abc" num=10 # Use [] to perform string comparisonif [ "$var" = "abc" ]; then echo "Strings equal" fi # Use [[]] to perform string comparisonif [[ "$var" == "abc" ]]; then echo "Strings equal" fi # Use [] to perform numerical comparisonsif [ $num -eq 10 ]; then echo "Equal values" fi # Use [[]] to perform numerical comparisonsif [[ $num == 10 ]]; then echo "Equal values" fi
Overall, [[]] provides more functionality and is easier to use and read in some cases, but it is an extension of Bash and may not be supported in other shells. If you are writing Bash scripts, [[]] is a more powerful and flexible option.
This is all about this article about the difference between [] and [[]] in shell scripts. For more relevant contents of the difference between [] and [[]] in shell scripts, please search for my previous articles or continue browsing the related articles below. I hope everyone will support me in the future!