2017-07-25 61 views
-3

我最近学习了如何在shell中编程。 我不明白为什么这两个声明产生不同的输出。看起来如果没有空格,测试将10==11作为一个字符串并始终返回true。Linux shell:条件语句中的空格

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

输入'help test'来查看帮助页面 – hek2mgl

+0

你是对的;如果没有空格,那么'test'命令没有多个参数来解析;它是一个单独的字符串,由于它不为null,所以它的计算结果为true。 – ghoti

+0

如果它帮助您记住使用空格,请使用-eq而不是==(编写10-eq11更困难,不要对自己说“我认为我应该在那里放一些空格”) –

回答

0
# 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" ] 
+0

谢谢,非常详细的解释。我想我应该更多地使用男人。 –

+0

@ lyu.l欢迎您 –