I was wondering if there is an efficient way to check if an element is present within an array in Bash? I am looking for something similar to what I can do in Python, like:
arr = ['a','b','c','d']
if 'd' in arr:
do your thing
else:
do something
I’ve seen solutions using associative array for bash for Bash 4+, but I am wondering if there is another solution out there.
Please understand that I know the trivial solution is to iterate in the array, but I don’t want that.
You could do:
This will give false positives for example if you look for “a b” — that substring is in the joined string but not as an array element. This dilemma will occur for whatever delimiter you choose.
The safest way is to loop over the array until you find the element:
Here’s a “cleaner” version where you just pass the array name, not all its elements
For associative arrays, there’s a very tidy way to test if the array contains a given key: The
-voperatorSee 6.4 Bash Conditional Expressions in the manual.