Why my string comparison isn't working in bash?

81 views Asked by At

I've a script that does something like this:

set -x

myJson="echo '{\"data\":\"true\"}'"

commandOutput=$(eval $myJson | jq '.data')

echo $commandOutput

while :
do
    if [[ $commandOutput == "true" ]]
    then
        break
    fi
    sleep 1
done

echo "Done"

However, my string comparison never works. The only way I managed this to work was putting '"true"' in the string comparison. It seems that is something related to the eval. Since I've set the x flag here is the output of this script:

+ myJson='echo '\''{"data":"true"}'\'''
++ eval echo ''\''{"data":"true"}'\'''
+++ echo '{"data":"true"}'
++ jq .data
+ commandOutput='"true"'
+ echo '"true"'
"true"
+ :
+ [[ "true" == \t\r\u\e ]]
+ sleep 1
+ :
+ [[ "true" == \t\r\u\e ]]
+ sleep 1
+ :
+ [[ "true" == \t\r\u\e ]]
+ sleep 1

It seems that the string at the right side is being always scaped, if this is the case why is this happening?

1

There are 1 answers

0
user1934428 On

As you can see from the trace which you have posted, commandOutput does not hold the string true, but the string "true", so you have to test for this:

 [[ $commandOutput == '"true"' ]]