1

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>]

?

djifan23
  • 11
  • 2
  • Does this answer your question? [How to represent multiple conditions in a shell if statement?](https://stackoverflow.com/questions/3826425/how-to-represent-multiple-conditions-in-a-shell-if-statement) – Shawn Feb 20 '21 at 20:40

2 Answers2

1

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.

Gerard H. Pille
  • 2,528
  • 1
  • 13
  • 17
0

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.

ilkkachu
  • 6,221
  • 16
  • 30