0

I have an array like:

moduleList=(AB, ABCdef, ABCd)

My array is numerically-indexed array not an associative array. I want to do an exact match for each element in array and to perform certain tasks.

Currently I'm doing like:

if [[  ${moduleList["AB"]}  ]]; then
    #do this.
fi



if [[  ${moduleList["ABCdef"]}  ]]; then
    #do that.
fi

But both the conditions are getting true as "AB" is there in each word. How can I distinguish each condition based on an exact match.

3
  • @steeldriver, they evaluate to the value of the named variable, recursively. Try x=y; y=1; echo $((x)) (or even x=y; y=x; echo $((x)), which does give an error).
    – ilkkachu
    Commented Mar 20, 2020 at 14:06
  • @ilkkachu or in a better example (which I think I've first seen in a post from Stéphane Chazelas): x='q[$(cat /etc/passwd >/dev/tty)]'; AB=x; echo "$AB ${moduleList["AB"]}"
    – user313992
    Commented Mar 20, 2020 at 14:20
  • @mosvy, yeah, the thing with indexes and expansions is the next one up.
    – ilkkachu
    Commented Mar 20, 2020 at 14:23

1 Answer 1

1

${moduleList["AB"]} or the same without the quotes takes the value of a variable called AB, and uses that as the index. If that variable is not set, the value you get is zero, and that expands to AB, the zeroth item of the array. That's a non-empty string, so it's truthy.

But both the conditions are getting true as "AB" is there in each word.

This, quite simply, is not the reason. You'd get the same with ${moduleList["x"]}, or whatever. Or, if the named variable is set to a number, you get the appropriate item in the array:

$ moduleList=(AB, ABCdef, ABCd)
$ unset x
$ echo "${moduleList[x]}"
AB,
$ x=2
$ echo ${moduleList["x"]}
ABCd

You'll have to loop over the array to find if a matching string exists, or change into an associative array and use the strings in as keys.

Also note that you probably don't want the commas in the assignment, you get literal commas in the values, as seen above.

7
  • @BiswajitMaharana Instead of looping over the array, something like this may do case " ${moduleList[@]} " in *" AB "*) ... do if val found ;; esac
    – user313992
    Commented Mar 20, 2020 at 18:39
  • @mosvy I can't use switch case as I have to check each element in array and do the logic. Commented Mar 22, 2020 at 4:28
  • You can perfectly replace the code you posted with case ... esacs as in my example. If you had something else in mind, you should've posted that.
    – user313992
    Commented Mar 22, 2020 at 4:31
  • @mosvy case ... esac works like if ... elif. But what I need is multiple if .. if statement so that each condition should be validated Commented Mar 22, 2020 at 4:46
  • Use multiple case ... esac ;-) Either the array is small and it doesn't matter, or the array is large, and then it's much faster than a loop.
    – user313992
    Commented Mar 22, 2020 at 4:52

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .