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

?

1

2 Answers 2

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.

Sign up to request clarification or add additional context in comments.

7 Comments

I didn't. Why do you think so? "[" is a link to "test".
@djifan23 He's correcting your syntax for your second snippet. But see mywiki.wooledge.org/…
@Shawn That link got me WTF'ing, until I read the comments. ;-)
? It seems straightforward... And what comments?
If you follow the link, the first thing you see is an invalid statement. A lot of emphasis on what you should NOT do.
|
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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.