【问题标题】:Using the && operator in an if statement在 if 语句中使用 && 运算符
【发布时间】:2013-04-30 01:19:12
【问题描述】:

我有三个变量:

VAR1="file1"
VAR2="file2"
VAR3="file3"

如何在 if 语句中使用 and (&&) 运算符,如下所示:

if [ -f $VAR1 && -f $VAR2 && -f $VAR3 ]
   then ...
fi

当我编写此代码时,它会出错。什么是正确的方法?

【问题讨论】:

    标签: bash if-statement syntax operators


    【解决方案1】:

    因此,为了使您的表达有效,将&& 更改为-a 就可以了。

    这样说是对的:

     if [ -f $VAR1 ] && [ -f $VAR2 ] && [ -f $VAR3 ]
     then  ....
    

    或喜欢

     if [[ -f $VAR1 && -f $VAR2 && -f $VAR3 ]]
     then  ....
    

    甚至

     if [ -f $VAR1 -a -f $VAR2 -a -f $VAR3 ]
     then  ....
    

    您可以在这个问题bash : Multiple Unary operators in if statement 中找到更多详细信息,以及那里给出的一些参考资料,例如What is the difference between test, [ and [[ ?

    【讨论】:

    • 请注意,POSIX 建议在 -a-o 上使用带有单括号符号的 &&||,因此如果您正在编写可移植代码,请使用第一个符号, 否则第二个并跳过第三个,特别是因为如果您需要对表达式进行分组,它会变得笨拙且难以阅读。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2017-03-06
    • 2013-03-19
    • 2011-05-15
    • 1970-01-01
    • 2012-12-28
    相关资源
    最近更新 更多