0
0
Bash-scriptingHow-ToBeginner · 2 min read

Bash Script to Find Common Elements in Two Arrays

Use nested loops in Bash to compare elements of two arrays and print common ones, for example: for i in "${arr1[@]}"; do for j in "${arr2[@]}"; do [[ "$i" == "$j" ]] && echo "$i"; done; done.
📋

Examples

Inputarr1=(1 2 3) arr2=(2 3 4)
Output2 3
Inputarr1=(apple banana cherry) arr2=(banana grape apple)
Outputapple banana
Inputarr1=(dog cat) arr2=(bird fish)
Output
🧠

How to Think About It

To find common elements, compare each item in the first array with every item in the second array. When a match is found, print or save that element. This simple approach works well for small arrays.
📐

Algorithm

1
Get the first array and the second array.
2
For each element in the first array, check every element in the second array.
3
If an element from the first array matches one in the second, record or print it.
4
Continue until all elements in the first array are checked.
5
Return or display all common elements found.
💻

Code

bash
arr1=(1 2 3 4)
arr2=(3 4 5 6)

for i in "${arr1[@]}"; do
  for j in "${arr2[@]}"; do
    if [[ "$i" == "$j" ]]; then
      echo "$i"
    fi
  done
 done
Output
3 4
🔍

Dry Run

Let's trace arrays arr1=(1 2 3 4) and arr2=(3 4 5 6) through the code

1

Start with first element of arr1

i=1; compare with arr2 elements 3,4,5,6; no match

2

Next element of arr1

i=2; compare with arr2 elements 3,4,5,6; no match

3

Next element of arr1

i=3; compare with arr2 elements 3,4,5,6; match found at 3; print 3

4

Next element of arr1

i=4; compare with arr2 elements 3,4,5,6; match found at 4; print 4

arr1 elementarr2 elementMatch?
13No
14No
15No
16No
23No
24No
25No
26No
33Yes
34No
35No
36No
43No
44Yes
45No
46No
💡

Why This Works

Step 1: Nested loops compare elements

The outer loop picks each element from the first array, and the inner loop checks it against every element in the second array.

Step 2: Equality check with <code>==</code>

The script uses [[ "$i" == "$j" ]] to test if elements are the same.

Step 3: Print common elements

When a match is found, the element is printed immediately, showing all common items.

🔄

Alternative Approaches

Using associative arrays for faster lookup
bash
declare -A map
arr1=(1 2 3 4)
arr2=(3 4 5 6)

for i in "${arr1[@]}"; do
  map["$i"]=1
 done

for j in "${arr2[@]}"; do
  if [[ ${map["$j"]} ]]; then
    echo "$j"
  fi
 done
This method is faster for large arrays because it avoids nested loops by using a hash map.
Using grep with process substitution
bash
arr1=(apple banana cherry)
arr2=(banana grape apple)

comm -12 <(printf "%s\n" "${arr1[@]}" | sort) <(printf "%s\n" "${arr2[@]}" | sort)
This uses external commands and sorting to find common elements, which is efficient but requires sorted input.

Complexity: O(n*m) time, O(n) space

Time Complexity

The nested loops cause the script to check each element of the first array against every element of the second, resulting in O(n*m) time.

Space Complexity

The script uses no extra arrays except for input, so space is O(n) for storing the arrays themselves.

Which Approach is Fastest?

Using associative arrays reduces time to O(n+m) by trading space for speed, while nested loops are simpler but slower for large arrays.

ApproachTimeSpaceBest For
Nested loopsO(n*m)O(n)Small arrays, simplicity
Associative arraysO(n+m)O(n)Large arrays, faster lookup
Sorting + commO(n log n + m log m)O(n+m)When sorting is acceptable and external commands are allowed
💡
Use associative arrays in Bash 4+ for faster common element checks instead of nested loops.
⚠️
Forgetting to quote array elements in comparisons, causing errors with spaces or special characters.