52

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

到目前为止,我已经使用了contains(结果contains "" $a只返回0if$a是空字符串,尽管这似乎并不是在所有情况下对我都有效)和switch(使用 acase "what_i_want_to_match"和 a case '*')的组合。不过,这些方法似乎都不是特别……正确。

4

2 回答 2

51
  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
于 2012-06-19T22:09:12.597 回答
18

手册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

您也可以使用[and]代替test.

这是检查空字符串未定义变量的方法,这些在fish中是错误的。

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
于 2015-03-20T23:19:29.603 回答