check for element

Dealing with containers such as lists or arrays you may want to code a condition like ‘does the array A contains an element (equal to) e’.
How to do this in bash? There are vivid discussions about this issue on relevant sites. As stated by tokland at

It’s an old question.

A frequently proposed solution is this.

A=(4 12 35 43)
if [[ ${A[@]} =~ $e ]] ; then
    echo "e=$e is in A"

It works fine under certain conditions.

e=5 is in A

If you actually want to rely on the outcome you should iterate over the array, see check-if-an-array-contains-a-value. This comes quite handy and you can even save some lines by using ;.

  1. grail said:

    If you are going to bag bash for doing something in a way you do not like, at least have the decency to write a snippet that would actually work. ‘A’ is the array not ‘a’, ‘b’ is never defined and ‘e’ is reassigned. Pretty much a garbage example

  2. rmbj said:

    Thank you, I corrected ‘a’ to ‘A’, ‘b’ to ‘e’ as it was meant to be. Sorry for that. Now the first display works as it is, and outputs ‘e=12 is in A’ as expected. The second display is the output with e=5 and its right, the reassigned is not shown because its supposed to be obvious from the output.

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )


Connecting to %s

%d bloggers like this: