我最近学习了如何在shell中编程。 我不明白为什么这两个声明产生不同的输出。看起来如果没有空格,测试将10==11
作为一个字符串并始终返回true。Linux shell:条件语句中的空格
$test 10==11 && echo yes || echo no
$yes
$test 10 == 11 && echo yes || echo no
$no
我最近学习了如何在shell中编程。 我不明白为什么这两个声明产生不同的输出。看起来如果没有空格,测试将10==11
作为一个字符串并始终返回true。Linux shell:条件语句中的空格
$test 10==11 && echo yes || echo no
$yes
$test 10 == 11 && echo yes || echo no
$no
# 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
等同
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" ]
谢谢,非常详细的解释。我想我应该更多地使用男人。 –
@ lyu.l欢迎您 –
输入'help test'来查看帮助页面 – hek2mgl
你是对的;如果没有空格,那么'test'命令没有多个参数来解析;它是一个单独的字符串,由于它不为null,所以它的计算结果为true。 – ghoti
如果它帮助您记住使用空格,请使用-eq而不是==(编写10-eq11更困难,不要对自己说“我认为我应该在那里放一些空格”) –