38

I have two variables

var=""
var1=abcd

Here is my shell script code

if [ $var == $var1 ]; then
  do something
else
  do something
fi

If I run this code it will prompt a warning

[: ==: unary operator expected

How can I solve this?

3
  • To format code in a post, just highlight it and click the "{}" icon (or indent it by 4 spaces). Your code was marked with > (which denotes quoted text, not formatted code) and unnecessary <br> tags. I fixed it. Commented Mar 22, 2013 at 15:16
  • There are numerous other questions on StackOverflow dealing with the need to quote variables in case they are unset or null-valued. Commented Mar 22, 2013 at 15:19
  • Just a reminder: To indicate that an answer solved your problem, you can click the green arrow to "accept" it. Which answer to accept, and whether to accept an answer at all, is entirely up to you. Commented Mar 22, 2013 at 18:39

2 Answers 2

110

Since the value of $var is the empty string, this:

if [ $var == $var1 ]; then

expands to this:

if [ == abcd ]; then

which is a syntax error.

You need to quote the arguments:

if [ "$var" == "$var1" ]; then

You can also use = rather than ==; that's the original syntax, and it's a bit more portable.

If you're using bash, you can use the [[ syntax, which doesn't require the quotes:

if [[ $var = $var1 ]]; then

Even then, it doesn't hurt to quote the variable reference, and adding quotes:

if [[ "$var" = "$var1" ]]; then

might save a future reader a moment trying to remember whether [[ ... ]] requires them.

Sign up to request clarification or add additional context in comments.

1 Comment

Same error coming on greater than or less than operator. How to solve that as number comparison. if [ $var -gt $var1 ]
1

Why all people want to use '==' instead of simple '=' ? It is bad habit! It used only in [[ ]] expression. And in (( )) too. But you may use just = too! It work well in any case. If you use numbers, not strings use not parcing to strings and then compare like strings but compare numbers. like that

let -i i=5 # garantee that i is nubmber
test $i -eq 5 && echo "$i is equal 5" || echo "$i not equal 5"

It's match better and quicker. I'm expert in C/C++, Java, JavaScript. But if I use bash i never use '==' instead '='. Why you do so?

1 Comment

Well, there are more convincing arguments than I'm an export in… Why you do so?. See for example: unix.stackexchange.com/a/16110/59743. It tells you that == is an alias for =. = is a standard operator, whereas == is widely implemented but it's not POSIX: pubs.opengroup.org/onlinepubs/9699919799/utilities/test.html

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.