Archive

Monthly Archives: August 2016

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 superuser.com:

It’s an old question.

A frequently proposed solution is this.

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

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 ;.

Advertisements