【问题标题】:Multiple conditions in if statement shell script [duplicate]if语句shell脚本中的多个条件[重复]
【发布时间】:2014-06-25 21:25:35
【问题描述】:

我想知道在编写 shell 脚本时是否可以在 if 语句中包含两个以上的语句?

username1="BOSS1"
username2="BOSS2"
password1="1234"
password2="4321"

if(($username == $username1)) && (($password == password1)) || 
  (($username == $username2)) && (($password == password2)) ; then

这不起作用。但是有没有办法让它发挥作用?

谢谢!

【问题讨论】:

    标签: shell if-statement conditional account


    【解决方案1】:

    如果使用/bin/sh,您可以使用:

    if [ <condition> ] && [ <condition> ]; then
        ...
    fi
    

    如果使用/bin/bash,您可以使用:

    if [[ <condition> && <condition> ]]; then
        ...
    fi
    

    【讨论】:

      【解决方案2】:

      您正在尝试比较算术命令 (((...))) 中的字符串。请改用[[

      if [[ $username == "$username1" && $password == "$password1" ]] ||
         [[ $username == "$username2" && $password == "$password2" ]]; then
      

      请注意,我已将其简化为两个由|| 连接的单独测试,&amp;&amp; 已移至测试内部。这是因为 shell 运算符 &amp;&amp;|| 具有相同的优先级,并且只是从左到右计算。因此,a &amp;&amp; b || c &amp;&amp; d 与预期的( a &amp;&amp; b ) || ( c &amp;&amp; d ) 等价通常并不正确。

      【讨论】:

      • 还要注意空格。所有这些空间都需要在那里!它必须是 if [[ $username 而不是 if[[$username。与大多数其他编程语言不同,正确的空格在 shell 脚本中至关重要。
      猜你喜欢
      • 1970-01-01
      • 2012-09-02
      • 1970-01-01
      • 2016-12-13
      • 1970-01-01
      • 2014-04-12
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多