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

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

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 ==; thats the original syntax, and its a bit more portable.

If youre using bash, you can use the [[ syntax, which doesnt require the quotes:

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

Even then, it doesnt 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.

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

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

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

Leave a Reply

Your email address will not be published.