What is the order in which the test or [ expressions are evaluated in a bash script? Is it the same as the order in which they are written? Are they all evaluated?
In the following example:
if [ expr1 -a -n expr2 ]
will expr2 be evaluated if expr1 is false?
It’s been a long time since I used that particular syntax. Nowadays, I prefer:
since I know that these are short-circuited. The
bashman page specifically states:It doesn’t appear to state clearly one way or the other for the
[andtestvariant (using-a).However, in the interests of furthering your knowledge and mine (and an indication as to why open source is a good thing), I went trolling through the
bashsource code.It turns out that it’s not short-circuited in that case. The particular pieces of code are (compressed a bit for readability):
You can see in both those cases that it continues to interpret the expressions regardless of the state of the first expression.
That was from
bash2.5 but I’ve just checked the 4.1 source as well and it hasn’t changed. Source was pulled straight from the horse’s mouth.So. bottom line: it appears that all sub-expressions are evaluated when using
-aand-owithtestor[.