在Fish shell中测试字符串相等/字符串比较?

Lei*_*cki 42 fish

你如何比较Fish中的两个字符串(就像"abc" == "def"在其他语言中一样)?

到目前为止,我已经使用了一个组合contains(事实证明contains "" $a只有返回,0如果$a是空字符串,虽然在所有情况下似乎都不适用于我)和switch(使用a case "what_i_want_to_match"和a case '*').但是,这些方法似乎都不是特别正确.

Kei*_*wer 43

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

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

  if [ "abc" = "abc" ]
        echo "equal"
  end
  equal
Run Code Online (Sandbox Code Playgroud)

或一个班轮:

if [ "abc" = "abc" ]; echo "equal"; end
equal
Run Code Online (Sandbox Code Playgroud)

  • 较短的一个班轮:`[abc = abc]; 和回声相等" (4认同)
  • 是的,单个“=”也让我困惑。 (2认同)
  • 请注意,方括号及其内部之间必须有一个空格。`[`实际上是`test`命令的快捷方式,`]`是`test`的自变量,告诉它停止读取args。如果没有空格,则[[]不会解释为命令,和/或`]`不会作为参数。 (2认同)

Den*_*nis 11

有时您想要检查空字符串未定义的变量,这些变量在鱼类中是假的.

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.
Run Code Online (Sandbox Code Playgroud)

您也可以使用test而不是man test.

一个实际的例子是检查你是否在git分支中.

set var foo

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

if test "$var" = "foo"
  echo equal
end
Run Code Online (Sandbox Code Playgroud)