When writing if
blocks in bash, shellcheck tells me that &&
and ||
are preferred to using -a
and -o
.
Why? It is faster, or just simply a stylistic preference to make scripts look cleaner?
The specific message I get is:
^-- SC2166: Prefer [ p ] || [ q ] as [ p -o q ] is not well defined.
From the POSIX specification for
test
:Thus: Uses of
test
with more than three arguments -- and if you're using-a
or-o
, you're depending on that -- have no behavior explicitly specified by unextended POSIX.Now, why is this so? Because there are scenarios where the parser could Do The Wrong Thing depending on variable values.
Do you remember people giving advice to do stuff like this?
...it's silly and ancient, right? Actually, no! Consider the case where
foo=(
andbar=)
, and someone runs a command like this:That expands to the following:
...and how do we parse it? Well, it could be a grouping operator (yes,
test
was historically specified to support them), checking whether-a
is non-null; or it could be checking whether both(
and)
are non-empty strings themselves; it's ambiguous. This ambiguity is why-a
and-o
are no longer preferred syntax.So, what does the replacement look like? Instead of:
...you'd write this:
...closing the two test expressions and using shell syntax to combine their output. Since
[
/test
is a shell builtin, it doesn't need to be executed as an external command, so this doesn't have the kind of performance overhead it would have back in the 70s when runningtest
meant invoking/usr/bin/test
.