Search code examples
bashshellif-statementreturn-valuestring-comparison

String Comparison in Bash Script Not Working As Expected


I have a bash script that calls another bash script and gets a string return value from that second script. I then try to compare that string to a hardcoded value and, even though I think it's right, it's skipping the if statement and going to the else.

Here's some code, just changed variable names:

returnVar=$(/bin/sh ./returnVar.sh ${1})

echo variable from second script = $returnVar

if [ "$returnVar" == "Value-Enabled false" ] ;  then 
    variableName="variable1"
    #do other stuff here


elif [ "$returnVar" == "Value-Enabled true" ] ; then 
    variableName="variable2"
    #do other stuff here

else 
    echo error  
    exit 1
fi

This staement:

echo variable from second script = "$returnVar"

seems to return the answer I want, "Value-Enabled false", but the comparison is not working. Can anyone see where I'm going wrong and know how to help?

I have also tried hardcoding the returnVar as the string I want, which then works! So something's going wrong that I don't know about.

Thanks in advance!


Solution

  • Finally got it! This is the new code that works for me:

    returnVar=$(/bin/sh ./returnVar.sh ${1})
    
    newVar=$(echo "${returnVar}" | tr -d '\n')
    
    if [ "${newVar}" == "Value-Enabled false" ] ;  then 
        variableName="variable1"
        #do other stuff here
    
    
    elif [ "${newVar}" == "Value-Enabled true" ] ; then 
        variableName="variable2"
        #do other stuff here
    
    else 
        echo error  
        exit 1
    fi
    

    saved the new value into variable called newVar, and added curly brackets around newVar in the if statements.