Often you may want to find the difference between two arrays using Bash.
You can use the following syntax to do so:
array3=(`echo ${array1[@]} ${array2[@]} | tr ' ' '\n' | sort | uniq -u `)
This particular example will find the elements that are different between the arrays named array1 and array2, then store the results in a new array named array3.
Here is how this syntax works:
- echo ${array1[@]} ${array2[@]}: Output all elements from both arrays
- tr ‘ ‘ ‘\n’: Replace all spaces with newlines so all elements are on their own line
- sort: Sort all elements
- uniq -u: Only display unique elements
The following example shows how to use this syntax in practice.
Example: How to Find the Difference Between Two Arrays in Bash
Suppose that we create the following two arrays named array1 and array2:
array1=(team1 team2 team3 team4 team5 team6 team7 team8)
array2=(team1 team4 team5 team6 team7)
Suppose that we would like to find the difference between these two arrays.
We can use the following syntax to do so:
array3=(`echo ${array1[@]} ${array2[@]} | tr ' ' '\n' | sort | uniq -u `)
We can then use the following syntax to view the elements in array3:
echo "${array3[@]}"
The following screenshot shows how to use this syntax in practice:

Notice that when we use the echo statement to view the contents of array3 we can see that it contains the following elements:
- team2
- team3
- team8
These represent the elements that are different between the arrays named array1 and array2.
Feel free to use similar syntax to find the difference between your own two arrays.
Related Tutorials
The following tutorials explain how to perform other common tasks in Bash:
Bash: How to Find the Intersection of Two Arrays
Bash: How to Get the Index of an Item in Array
Bash: How to Iterate Over Two Arrays at Once
