Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

unary operator expected in shell script when comparing null value with string

Tags:

shell

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?

like image 616
Uvais Ibrahim Avatar asked Mar 22 '13 15:03

Uvais Ibrahim


People also ask

What is unary operator in shell script?

The word unary is basically synonymous with “single.” In the context of mathematics, this could be a single number or other component of an equation. So, when Bash says that it is expecting a unary operator, it is just saying that you are missing a number in the script.

What is $? == 0 in shell script?

$? is the exit status of the most recently-executed command; by convention, 0 means success and anything else indicates failure. That line is testing whether the grep command succeeded. The grep manpage states: The exit status is 0 if selected lines are found, and 1 if not found.

What is $$ and $# in shell scripting?

Inside the function, $1 expands to the first positional parameter that was passed to the shell function, rather than to the script it's part of. Thus, like $# , the special parameters $1 , $2 , etc., as well as $@ and $* , also pertain to the arguments passed to a function, when they are expanded in the function.


1 Answers

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.

like image 98
Keith Thompson Avatar answered Oct 19 '22 23:10

Keith Thompson