在fish shell中,如何在if语句中放入两个条件?

问题描述 投票:0回答:4

我想用 bash 做什么:

> if true; then echo y; else echo n; fi
y
> if false; then echo y; else echo n; fi
n
> if false || true; then echo y; else echo n; fi
y

现在尝试用鱼:

> if true; echo y; else; echo n; end
y
> if false; echo y; else; echo n; end
n

# Here 'or true' are just two arguments for false
> if false or true; echo y; else; echo n; end 
n

# Here 'or true;' is a command inside the if
> if false; or true; echo y; else; echo n; end 
n

# Can't use command substitution instead of a command
> if (false; or true); echo y; else; echo n; end
fish: Illegal command name “(false; or true)”

如何在一个

if
中拥有两个条件?

if-statement fish
4个回答
30
投票

另外两种方法:

方法一:

    if begin false; or true; end
      echo y
    else
      echo n
    end

方法二:

    false; or true
    and echo y
    or echo n

2
投票

这种方法可行,但这是一个丑陋的黑客:

> if test (true; and echo y); echo y; else; echo n; end 
y
> if test (false; and echo y); echo y; else; echo n; end 
n
> if test (false; or true; and echo y); echo y; else; echo n; end 
y

我真诚地希望得到更好的答案。


2
投票

从fish 2.3b1开始,可以直接在

if
条件下使用
and
/
or
链接命令。
begin ... end
不再需要了。官方文档已于2016年5月更新

所以现在这按预期工作了:

> if false; or true; echo y; else; echo n; end
y

0
投票

对于任何寻找测试表达式的人:您可以执行以下操作(如果

$i
低于
$m
或大于
$n
):

if [ $i -lt $m ] || [ $i -gt $n ]
    echo "Voila!"
end
© www.soinside.com 2019 - 2024. All rights reserved.