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

后端 未结 2 1291
逝去的感伤
逝去的感伤 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.

    0 讨论(0)
  • 2020-12-29 04:28

    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?

    0 讨论(0)
提交回复
热议问题