Check if a Bash array contains a value
Codemia Knowledge Hub ·
Bash arrays have no built-in contains method. The safest check is a small loop that compares each element exactly with [[ ... == ... ]]. Shorter one-liners exist, but many break when values contain spaces, glob characters, or substrings of other values.
Loop and compare each element
Each array element is passed as a separate argument, and the quoted expansion "${fruits[@]}" preserves spaces inside elements.
Why the one-line regex trick is risky
You will often see this:
It is compact but fragile, and can give false positives when:
- one element is a substring of another
- values contain spaces
- values contain regex metacharacters
- globbing and word splitting are not handled carefully
For example, searching for app in an array containing apple should be false for exact membership, but string tricks can easily report a match. For exact membership, explicit iteration is easier to trust and maintain.
Associative array for repeated lookups
If you test membership many times, build an associative array once and use its keys as a lookup table:
Setup costs more up front, but every later lookup is simple. The ${seen[banana]+x} pattern checks whether the key exists even if its value is empty, which is more reliable than testing the value directly.
Indexed or associative from the start
An indexed array stores values by position; an associative array stores them by key. Use an indexed array when order matters, and an associative array when membership matters. Scripts often start with indexed arrays and become awkward once repeated membership checks appear, which is a sign the data structure should change.
Mistakes to avoid
- Expanding with
${array[*]}when you needed"${array[@]}". - Using substring or regex tricks for exact membership checks.
- Forgetting that elements may contain spaces or special characters.
- Testing associative-array membership by value instead of by key existence.
Related reading
- Check if a binary tree is a mirror image or symmetric
- Check if a given key already exists in a dictionary
- Check if a given key already exists in a dictionary and increment it
- Check if a list is a rotation of another list that works with duplicates
- check if a tree is a binary search tree
- Check if a value exists in ArrayList
- Check if a value is in an array C
- Check if all elements in a list are equal

DSA Fundamentals
Master algorithmic patterns and data structures through hands-on LeetCode-style problems - from arrays and hashing to dynamic programming and advanced graphs.
View the courseData Structures & Algorithms practice on Codemia
Step through 300+ coding interview problems with animated visualisers that show the data structure changing as the code runs. The Blind 75 are free.