【问题标题】:Linux shell: space in condition statementLinux shell:条件语句中的空格
【发布时间】:2017-07-25 12:28:07
【问题描述】:

我最近学习了如何在 shell 中编程。 我不明白为什么这两个语句会产生不同的输出。看来如果没有空格,test 把10==11 当作一个字符串,总是返回true。

$test 10==11 && echo yes || echo no
$yes
$test 10 == 11 && echo yes || echo no
$no

【问题讨论】:

  • 输入help test查看帮助页面
  • 你说得对;如果没有空格,则test 命令没有多个参数要解析;它是一个单一的字符串,它的计算结果为真,因为它不为空。
  • 如果它可以帮助你记住使用空格,请使用 -eq 而不是 == (写 10-eq11 而不是对自己说“我想我应该在里面放一些空格”更难)

标签: linux shell command-line


【解决方案1】:
# single string, not null so true, and result is yes
test 10==11 && echo yes || echo no

# there exist space 10 == 11 not equal string comparison so result no
test 10 == 11 && echo yes || echo no

Read More Here

等价物

if test 10==11; then echo yes; else echo no; fi
yes

if test 10 == 11; then echo yes; else echo no; fi
no

# or this same as above
if test 10 = 11; then echo yes; else echo no; fi
no

来自http://tldp.org/LDP/abs/html/comparison-ops.html

string comparison

=

    is equal to

    if [ "$a" = "$b" ]

    Caution 

    Note the whitespace framing the =.

    if [ "$a"="$b" ] is not equivalent to the above.
==

    is equal to

    if [ "$a" == "$b" ]

【讨论】:

  • 谢谢,非常详细的解释。我认为我应该更多地使用 man。
猜你喜欢
  • 2015-03-03
  • 2020-11-11
  • 2014-09-26
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-06-25
相关资源
最近更新 更多