[英]Shell Scripting: How to do multiple conditions in if else statement
How should I phrase an if statement with multiple conditions:我应该如何用多个条件来表达 if 语句:
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".正如“man test”所展示的那样,“-a”代表“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. &&
是 shell 运算符,在cmd1 && cmd2
中,它告诉 shell 如果第一个命令成功,则只运行第二个命令。
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.要运行的命令将是
[ "$x" = a
and "$y" = b ]
,其中第一个将给出缺少]
参数的错误。 (Here, it's good to remember that [
is a regular command, similar to echo
or so, it just has a funny name.) (在这里,请记住
[
是一个常规命令,类似于echo
左右,它只是有一个有趣的名字。)
Also, you should avoid this:此外,您应该避免这种情况:
if [ "$x" = a -a "$y" = b ]; then ...
even though it works in some shells in simple cases.即使它在一些简单的情况下也可以在某些 shell 中工作。 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.同样,由于
[
是一个常规命令,而不是特殊的 shell 语法,它无法分辨哪个 arguments 来自变量,哪些是硬编码运算符。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.