lundi 24 septembre 2018

If Statement - Literal String Comparison Not Working as Expected

I'm having trouble comparing two strings within an if statement using double brackets. Here is what I have below. The $statusID variable is pulled from a file elsewhere and will pull either exactly "HELLO" or "WORLD" but when used below the string doesn't match and ends up using the else statement instead.

 if [[ "$statusID" == "HELLO" ]]; then
     #DO SOMETHING HERE
 elif [[ "$statusID" == "WORLD" ]]; then
     #DO SOMETHING ELSE
 else
     #DO SOMETHING ELSE AGAIN
 fi

I've tried using wildcards which will work but causes problems when I have a similar variable later such as "HIHELLO" it runs the "HELLO" if statement instead of "HIHELLO". I don't want to use this method because of that problem.

 if [[ "$statusID" == *"HELLO"* ]]; then
     #DO SOMETHING HERE
 elif [[ "$statusID" == *"WORLD"* ]]; then
     #DO SOMETHING ELSE
 else
     #DO SOMETHING ELSE AGAIN
 fi

I'm trying to compare the literal value of the strings. If the value of $statusID is HELLO I want the if statement to be true and run that code. I've looked at other similar posts on stack overflow and a few other sites but I'm not understanding what I'm missing. Is it how I'm pulling the variable? Is it how I'm comparing them?

I will note that if I set the variable directly such as:

 statusID="HELLO" or statusID=HELLO

within terminal directly (as opposed to running a script) it seems to match properly.

Aucun commentaire:

Enregistrer un commentaire