if语句shell脚本中的多个条件

use*_*466 6 account shell conditional if-statement

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

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

if(($username == $username1)) && (($password == password1)) || 
  (($username == $username2)) && (($password == password2)) ; then
Run Code Online (Sandbox Code Playgroud)

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

谢谢!

net*_*tux 30

如果使用/bin/sh你可以使用:

if [ <condition> ] && [ <condition> ]; then
    ...
fi
Run Code Online (Sandbox Code Playgroud)

如果使用/bin/bash你可以使用:

if [[ <condition> && <condition> ]]; then
    ...
fi
Run Code Online (Sandbox Code Playgroud)


che*_*ner 10

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

if [[ $username == "$username1" && $password == "$password1" ]] ||
   [[ $username == "$username2" && $password == "$password2" ]]; then
Run Code Online (Sandbox Code Playgroud)

请注意,我已经将这个减少到两个单独的测试连接||,并&&在测试中移动.这是因为外壳运营商&&||具有相同的优先级,并简单地从左边的评价权.结果,通常不a && b || c && d等于预期的( a && b ) || ( c && d ).

  • 关于空白也要小心.所有这些空间都需要在那里!它必须是`if [[$ username`而不是`if [[$ username`.与大多数其他编程语言不同,正确的空格在shell脚本中至关重要. (2认同)