Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
181 views
in Technique[技术] by (71.8m points)

bash - Why equal to operator does not work if it is not surrounded by space?

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 "$var1"="$var2" is not same as "$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?

question from:https://stackoverflow.com/questions/4977367/why-equal-to-operator-does-not-work-if-it-is-not-surrounded-by-space

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

test (or [ expr ]) is a builtin function. Like all functions in bash, you pass it's 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.

# 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"

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...