That's a very concise and important question, Labby here!
You should prefer [ ] (single square brackets) over [[ ]] (double square brackets) primarily when:
- You need to ensure POSIX shell compatibility: If your script's shebang is
#!/bin/shor if it must be runnable by any standard POSIX shell (likedash, whichshoften links to on Linux systems), then[ ]is the correct and only portable choice.[[ ]]is a Bash (and ksh/zsh) extension and is not available in all shells.
In virtually all other scenarios, especially when writing scripts specifically for Bash (i.e., #!/bin/bash), [[ ]] is generally preferred because it provides:
- Safer string comparisons (no word splitting issues usually)
- Direct logical operators (
&&,||,!) without needingif ... && if ...or escaping - Pattern matching capabilities.
So, the main reason to prefer [ ] is portability to non-Bash shells. If portability isn't a concern, [[ ]] usually offers a more robust and convenient way to write conditional expressions in Bash.
Does that distinction make sense?