1

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 ?

Itération 122442
  • 2,644
  • 2
  • 27
  • 73
  • 3
    To access array index use: `"${ERRORS[TEST]}"` – anubhava Apr 08 '20 at 06:44
  • 1
    @anubhava: In quotes? Maybe it doesn't matter with `[[` but it feels sloppy to an old-time programmer (and the fact that the syntax inside `[[` is different from normal is one of the reasons I really dislike `[[`). – Jonathan Leffler Apr 08 '20 at 06:45
  • Yes I meant only for `[[ ... ]]` though it never hurts to use quotes *always* in shell – anubhava Apr 08 '20 at 06:46

1 Answers1

1

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.

Nemo Zhang
  • 146
  • 7