unary operator expected in shell script when comparing null value with string
shell
Solution
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.
Problem
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?