When should `[ ]` be preferred over `[[ ]]`?

QuestionsQuestions8 SkillsProDec, 15 2025
0100

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/sh or if it must be runnable by any standard POSIX shell (like dash, which sh often 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 needing if ... && 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?

0 Comments

no data
Be the first to share your comment!