如何在Fish shell中测试字符串的相等性/比较字符串?

62

在Fish中如何比较两个字符串(类似于其他语言中的"abc" == "def")?

到目前为止,我使用了contains的组合(结果发现contains "" $a只有当$a为空字符串时才返回0,但在某些情况下这似乎对我没用)和switch(使用case "要匹配的内容"case '*')。然而,这些方法都不是特别正确。


8
原来,[ 实际上是一个命令(在OS X上是/bin/[),同时也是Bash的内置命令,具有不同的语法。想象一下! - Daisy Leigh Brenecki
这个评论让我开心极了!"[ command" 是一个非常强大的工具。 - yagooar
7
个人而言,我已经开始在所有的脚本中使用test代替[,这样可以清晰地表明它是一个外部命令而不是语言的一部分。(test[是完全相同的工具。) 当然,我认为test也是Bash内置命令。 - Daisy Leigh Brenecki
2
我应该更新一下,指出在 Fish 2.x 中,test[ 都是内置命令。但是,它们的语法与外部 [ 命令相同,因此接受的答案仍然是正确的。 - Daisy Leigh Brenecki
2个回答

59
  if [ "abc" != "def" ] 
        echo "not equal"
  end
  not equal

  if [ "abc" = "def" ]
        echo "equal"
  end

  if [ "abc" = "abc" ]
        echo "equal"
  end
  equal
或者一行代码:
if [ "abc" = "abc" ]; echo "equal"; end
equal

1
啊哈!奇怪,我以为我之前试过方括号了;也许是单个的 = 让我困惑了。 - Daisy Leigh Brenecki
2
是的,单个“=”符号也让我感到困惑。 - Keith Flower
4
[ abc = abc ]; 并且 echo equal。(翻译者注:这段代码是一条简单的 Bash 命令,意思是将变量 abc 赋值为字符串"abc",然后输出字符串"equal"。) - kzh
我喜欢它。作为一个bash用户,我必须说fish做得很好! - smac89
3
请注意,方括号内部和外部之间必须有一个空格。[实际上是test命令的快捷方式,]是告诉test停止读取参数的参数。如果没有空格,则[不会被解释为命令和/或]不存在作为参数。 - BallpointBen
@BallpointBen,感谢你的提醒。你提到的[之间的空格让我疯狂了。幸运的是你指出了它。你救了我的一天,兄弟! - LeOn - Han Li

24

test 的手册提供了一些有用的信息。可以通过 man test 命令来获取。

Operators for text strings
   o STRING1 = STRING2 returns true if the strings STRING1 and STRING2 are identical.

   o STRING1 != STRING2 returns true if the strings STRING1 and STRING2 are not
     identical.

   o -n STRING returns true if the length of STRING is non-zero.

   o -z STRING returns true if the length of STRING is zero.
例如。
set var foo

test "$var" = "foo" && echo equal

if test "$var" = "foo"
  echo equal
end

您还可以使用[]代替test

以下是检查在fish中falsy的空字符串未定义变量的方法。

set hello "world"
set empty_string ""
set undefined_var  # Expands to empty string

if [ "$hello" ]
  echo "not empty"  # <== true
else
  echo "empty"
end

if [ "$empty_string" ]
  echo "not empty"
else
  echo "empty"  # <== true
end

if [ "$undefined_var" ]
  echo "not empty"
else
  echo "empty"  # <== true
end

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接