如果没有空间,为什么等于运算符不起作用? [英] Why equal to operator does not work if it is not surrounded by space?

查看:74
本文介绍了如果没有空间,为什么等于运算符不起作用?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我尝试了以下脚本

#!/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" ] 

并打印Not equal

为什么会这样?为什么"$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(或[ 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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆