Reputation: 11
How should I phrase an if statement with multiple conditions:
if [ <T/F Condition> ] && [ <T/F Condition> ] && [ <T/F Condition> ]
or
if [ <T/F Condition> && <T/F Condition> && <T/F Condition>]
?
Upvotes: 1
Views: 2441
Reputation: 6517
The &&
is a shell operator, in cmd1 && cmd2
, it tells the shell to only run the second command if the first succeeds.
So, this works, and does what you want:
if [ "$x" = a ] && [ "$y" = b ]; then ...
However, in this:
if [ "$x" = a && "$y" = b ]; then ...
The commands to run would be [ "$x" = a
and "$y" = b ]
, the first of which will give an error for the missing ]
argument. (Here, it's good to remember that [
is a regular command, similar to echo
or so, it just has a funny name.)
Also, you should avoid this:
if [ "$x" = a -a "$y" = b ]; then ...
even though it works in some shells in simple cases. This has to do with parsing issues when the variables contain strings like !
(negation) or others that are operators for [
. Again, since [
is a regular command, and not special shell syntax, it can't tell which arguments come from variables and which are hardcoded operators.
Upvotes: 0
Reputation: 2578
As "man test" would've shown you "-a" stands for "and".
eg.:
if [ <T/F Condition> -a <T/F Condition> -a <T/F Condition> ]
Watch the spacing too.
Upvotes: 1