如果等于运算符没有被空格包围,为什么它不起作用?
我尝试了以下脚本:
#!/bin/bash
var1="Test 1"
var2="Test 2"
if [ "$var1"="$var2" ]
then
echo "Equal"
else
echo "Not equal"
fi
它给了我Equal
。虽然它应该打印 Not equal
只有当我在 =
周围插入空格时,它才按预期工作:
if [ "$var1" = "$var2" ]
并打印 Not equal
为什么会这样?为什么 "$var1"="$var2"
与 "$var1" = "$var2"
不同?
而且,当我写if [ "$var1"= "$var2" ]
时,它给出了
line 4: [: Test 1=: unary operator expected
什么意思?为什么它需要一元运算符?
I tried the following script:
#!/bin/bash
var1="Test 1"
var2="Test 2"
if [ "$var1"="$var2" ]
then
echo "Equal"
else
echo "Not equal"
fi
It gave me Equal
. Although it should have printed Not equal
Only when I inserted space around =
it worked as intended:
if [ "$var1" = "$var2" ]
and printed Not equal
Why is it so? Why is "$var1"="$var2"
not same as "$var1" = "$var2"
?
Moreover, when I wrote if [ "$var1"= "$var2" ]
, it gave
line 4: [: Test 1=: unary operator expected
What does it mean? How come it's expecting a unary operator?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
test
(或[ expr ]
)是一个内置函数。与 bash 中的所有函数一样,您可以将其参数作为空格分隔的单词传递。正如 bash 内置函数的手册页所述:“每个运算符和操作数必须是一个单独的参数。”
这就是 bash 和大多数其他 Unix shell 的工作方式。
变量赋值不同。
在 bash 中,变量赋值的语法为:
name=[value]
。您不能在=
周围放置不带引号的空格,因为 bash 不会将其解释为您想要的赋值。 bash 将大多数单词列表视为带参数的命令。例如
test
(or[ expr ]
) is a builtin function. Like all functions in bash, you pass its arguments as whitespace separated words.As the man page for bash builtins states: "Each operator and operand must be a separate argument."
It's just the way bash and most other Unix shells work.
Variable assignment is different.
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.E.g.
当 shell 读取时,
它会调用带有 4 个参数的命令 [。 [ 是内置命令还是外部命令无关紧要,但可能有助于理解它可能是外部命令 /bin/[。第二个参数是文字“=”,第四个参数是“]”。但是,当 shell 读取
[ 时,仅获取 3 个参数:附加 '=' 的 $var1 扩展、$var2 扩展和 ']'。当它仅获得 3 个参数时,它期望最后一个参数为 ']',第一个参数为一元运算符。
When the shell reads
it invokes the command [ with 4 arguments. Whether [ is a builtin or an external command is irrelevant, but it may help to understand that it may be the external command /bin/[. The second argument is the literal '=' and the fourth is ']'. However, when the shell reads
[ only gets 3 arguments: the expansion of $var1 with '=' appended, the expansion of $var2, and ']'. When it gets only 3 arguments, it expects the last argument to be ']' and the first argument to be a unary operator.
为了补充现有的解释,
"$var1"="$var2"
只是一个非空字符串,因此在条件中始终计算为 true。上面的命令将始终打印出
true
(即使var1
和var2
为空)。To add to the existing explanation,
"$var1"="$var2"
is just a single non-empty string, and thus always evaluates as true in a conditional.The above command will always print out
true
(even ifvar1
andvar2
be empty).在 bash 中最好使用 [[ ]]:
In bash the best is to use [[ ]]: