简体   繁体   中英

Shell Scripting: How to do multiple conditions in if else statement

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

?

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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM