Itération 122442
Itération 122442

Reputation: 2972

Why is the check not working as I expect it to?

Using bash 4.2, I have an associative array.

I want to check if the value at a key contains or not a string. To achieve this, based on this topic, i do the following:

ERRORS[TEST]="TEST"
if [[ ! ERRORS[TEST] =~ "TEST" ]]; then
    echo "failed"
else
    echo "succeed"
fi

This should echo failed, but it echoes succeed.

What I am missing or not understanding in this behavior ? If my method is wrong, how can I achieve this ?

Upvotes: 1

Views: 39

Answers (1)

Nemo Zhang
Nemo Zhang

Reputation: 146

Use ${ERRORS[TEST]}. That is the way to get the value of associative array.

ERRORS[TEST] will just return the code as-is.

BTW, when ERRORS[TEST]="TEST", the code should echo "succeed". As you have a ! ahead of it, which means it echos "failed" when the variable does not contain "TEST". It would echo "succeed" as it actually contains one.

BTW x2, if you use ERRORS[TEST] instead of ${ERRORS[TEST]}, it would also echo "succeed". But it is not correctly working as it would always return "succeed" as "TEST" is included in "ERRORS[TEST]", regardless of the actual value of the variable.

Upvotes: 1

Related Questions