Bash Script to Check if Array Contains Element
if [[ "$element" == "$item" ]] inside to check each array item; for example, for item in "${array[@]}"; do if [[ "$item" == "$element" ]]; then echo "Found"; fi; done.Examples
How to Think About It
Algorithm
Code
array=(apple banana cherry) element=banana found=0 for item in "${array[@]}"; do if [[ "$item" == "$element" ]]; then found=1 break fi done if [[ $found -eq 1 ]]; then echo "Found" else echo "Not Found" fi
Dry Run
Let's trace the example where array=(apple banana cherry) and element=banana through the code
Initialize variables
array=(apple banana cherry), element=banana, found=0
Check first item
item=apple, compare with banana → no match, continue
Check second item
item=banana, compare with banana → match found, set found=1, break loop
| Iteration | item | found |
|---|---|---|
| 1 | apple | 0 |
| 2 | banana | 1 |
Why This Works
Step 1: Loop through array
The for loop goes through each element in the array one by one.
Step 2: Compare elements
Inside the loop, if [[ "$item" == "$element" ]] checks if the current item matches the element.
Step 3: Set flag and break
If a match is found, we set found=1 and break to stop checking further.
Step 4: Print result
After the loop, we print 'Found' if found is 1, otherwise 'Not Found'.
Alternative Approaches
contains_element() {
local e
for e in "${@:2}"; do
[[ "$e" == "$1" ]] && return 0
done
return 1
}
array=(apple banana cherry)
element=banana
if contains_element "$element" "${array[@]}"; then
echo "Found"
else
echo "Not Found"
fiarray=(apple banana cherry) element=banana if printf "%s\n" "${array[@]}" | grep -qx "$element"; then echo "Found" else echo "Not Found" fi
Complexity: O(n) time, O(1) space
Time Complexity
The script checks each element once, so time grows linearly with array size.
Space Complexity
Only a few variables are used, so space stays constant regardless of array size.
Which Approach is Fastest?
The loop with break is fastest for large arrays because it stops early; grep is simpler but always checks all elements.
| Approach | Time | Space | Best For |
|---|---|---|---|
| Loop with break | O(n) | O(1) | Large arrays, early exit |
| Function wrapper | O(n) | O(1) | Reusable code, clarity |
| grep with printf | O(n) | O(n) | Small arrays, quick scripts |
break to stop the loop early once the element is found for better performance.[[ ]] can cause errors or wrong matches.