【问题标题】:Test for string equality / string comparison in Fish shell?在 Fish shell 中测试字符串相等/字符串比较?
【发布时间】:2012-06-22 00:22:51
【问题描述】:

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

到目前为止,我已经使用了 contains 的组合(事实证明,如果 $a 是空字符串,contains "" $a 只会返回 0,尽管这似乎并不适用于所有情况) 和switch(带有case "what_i_want_to_match"case '*')。不过,这两种方法似乎都不是特别……正确。

【问题讨论】:

  • 所以,[ 实际上是一个命令(在 OS X 上为/bin/[),以及一个 Bash 内置,具有不同的语法。去图吧!
  • 这条评论让我很开心! [ 命令是一个非常强大的工具。
  • 就个人而言,我实际上已经开始在我的所有脚本中使用test 而不是[,因此很明显它是一个外部命令而不是语言的一部分。 (test[ 是完全相同的工具。)当然,我认为 test 也是 Bash 内置的。
  • 我可能应该更新这一点,指出在 Fish 2.x 中,test[ 都是内置的。但是,它们与外部[ 命令具有相同的语法,因此接受的答案仍然是正确的。

标签: fish


【解决方案1】:
  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

【讨论】:

  • 啊哈!奇怪,我以为我以前尝试过方括号;也许是单曲 = 让我大吃一惊。
  • 是的,单个的 '=' 也会让我感到困惑。
  • 较短的一个衬里:`[ abc = abc ];和回声相等”
  • 我喜欢。来自 bash,我必须说 fish 做得对!
  • 请注意,方括号和其中的内容之间必须有一个空格。 [ 实际上是 test 命令的快捷方式,]test 的参数,告诉它停止读取 args。没有空格,[ 不会被解释为命令和/或] 不会作为参数出现。
【解决方案2】:

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中是虚假的。

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

【讨论】:

    猜你喜欢
    • 2016-08-10
    • 2023-04-10
    • 2014-11-09
    • 2015-01-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多