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

后端 未结 2 1296
逝去的感伤
逝去的感伤 2020-12-29 03:54

I have two variables

var=\"\"
var1=abcd

Here is my shell script code

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


        
2条回答
  •  渐次进展
    2020-12-29 04:16

    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.

提交回复
热议问题