如果等于运算符没有被空格包围,为什么它不起作用? [英] Why equal to operator does not work if it is not surrounded by space?
问题描述
我尝试了以下脚本
#!/bin/bash
var1="Test 1"
var2="Test 2"
if [ "$var1"="$var2" ]
then
echo "Equal"
else
echo "Not equal"
fi
它给了我Equal
.虽然它应该打印Not equal
It gave me Equal
. Although it should have printed Not equal
仅当我在 =
周围插入空格时,它才能按预期工作
Only when I inserted space around =
it worked as intended
if [ "$var1" = "$var2" ]
并打印不等于
为什么会这样?为什么 "$var1"="$var2"
与 "$var1" = "$var2"
不同?
Why is it so? Why "$var1"="$var2"
is not same as "$var1" = "$var2"
?
此外,当我写if [ "$var1"="$var2" ]
时,它给了
Moreover, when I wrote if [ "$var1"= "$var2" ]
, it gave
line 4: [: Test 1=: unary operator expected
这是什么意思?它期待的一元运算符是怎么来的?
What does it it mean? How come its expecting unary operator?
推荐答案
test
(or [ expr ]
) 是一个内置函数.像 bash 中的所有函数一样,你将它的参数作为空格分隔的单词传递.
test
(or [ expr ]
) is a builtin function. Like all functions in bash, you pass it's arguments as whitespace separated words.
正如 bash 内置程序的手册页所述:每个运算符和操作数必须是一个单独的参数."
As the man page for bash builtins states: "Each operator and operand must be a separate argument."
这就是 bash 和大多数其他 Unix shell 的工作方式.
It's just the way bash and most other Unix shells work.
变量赋值不同.
在 bash 中,变量赋值的语法为:name=[value]
.您不能在 =
周围放置不带引号的空格,因为 bash 不会将其解释为您想要的分配.bash 将大多数单词列表视为带参数的命令.
In bash a variable assignment has the syntax: name=[value]
. You cannot put unquoted spaces around the =
because bash would not interpret this as the assignment you intend. bash treats most lists of words as a command with parameters.
例如
# call the command or function 'abc' with '=def' as argument
abc =def
# call 'def' with the variable 'abc' set to the empty string
abc= def
# call 'ghi' with 'abc' set to 'def'
abc=def ghi
# set 'abc' to 'def ghi'
abc="def ghi"
这篇关于如果等于运算符没有被空格包围,为什么它不起作用?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!