如何在 IF 语句中检查多个条件

如何在 IF 语句中检查多个条件

我试图在以下语句中测试多个条件if

If [[[ "$var1" = "$var2" || "$var1" = "$var3" || "$var1" = "$var4" ]]];

但是,当我执行上述语法时,出现错误。谁能帮我在 IF 语句中检查多个条件?

答案1

括号太多,不if应该大写。尝试这样:

if [[ "$var1" == "$var2" || "$var1" == "$var3" || "$var1" == "$var4" ]]; then

答案2

使用标准sh语法可能比使用(拼写错误,应该[[代替[[[ksh构造更容易:

case $var1 in
  "$var2" | "$var3" | "$var4") echo match;;
  *) echo no match;;
esac

答案3

[[ "$var1" == "$var2" || "$var1" == "$var3" || "$var1" == "$var4" ]]

或者,为了可读性,

[[ "$var1" == "$var2" ]] ||
[[ "$var1" == "$var3" ]] ||
[[ "$var1" == "$var4" ]]

或者与case,正如斯特凡·查泽拉斯建议的那样,或者对变量名称进行过于复杂的循环并使用名称引用(在bash或中ksh93),

for var in var2 var3 var4; do
    typeset -n v="$var"
    if [[ "$var1" == "$v" ]]; then
        # printf '%s has same value as var1\n' "$var"
        found=1
        break
    fi
done

if [[ "$found" -eq 1 ]]; then ...

相关内容