mattobob
mattobob

Reputation: 865

How to properly compare strings in bash

Strange behavior when comparing strings in bash:

        if [[ $line:0:1 =~ "BSID" ]]; then
           if [ "${line:6:2}" != "$m_BSID" ]; then
              SUCCESS="fail BSID: ${line:6:2} should be $m_BSID";
              echo $SUCCESS;
           fi
        fi

This is what I get:

fail BSID: 6 should be 6

here variable checks:

Content of $line: BSID: 6 (Dolby Digital)
declare -- m_BSID="6"

What am I doing wrong?

Upvotes: 0

Views: 95

Answers (1)

anubhava
anubhava

Reputation: 786091

You're comparing ${line:6:2} with $m_BSID in your if condition.

"${line:6:2}" will be a 2 digit string starting at index 6, whereas $m_BSID is just 6.

If you run:

echo "<${line:6:2}>"

You will get:

<6 >

that is one space after 6, of course "6 " is not equal to "6"

You should use:

if [[ "${line:6:1}" != "$m_BSID" ]]; then
   SUCCESS="fail BSID: ${line:6:1} should be $m_BSID"
   echo "$SUCCESS"
fi

Upvotes: 1

Related Questions