How to Get Unique Values from Array in Bash (With Example)


Often you may want to get only the unique values from an array in Bash.

You can use the following syntax to do so:

uniques=($(echo "${my_array[@]}" | tr ' ' '\n' | sort -u | tr '\n' ' '))

This particular example will get all unique values from the array named my_array and save the results in a new array named uniques.

Here is what the various commands do:

  • echo “${my_array[@]}”: Prints all elements from the array
  • tr ‘ ‘ ‘\n’: Replaces each space in the array with a line break
  • sort -u: Sorts and returns only the unique values ( -u )from the array
  • tr ‘\n’ ‘ ‘: Replaces each line break with a space

The following example shows how to use this syntax in practice.

Example: How to Get Unique Values from Array in Bash

Suppose that we create an array in Bash named $my_array that contains the names of various basketball teams:

my_array=(Mavs Hawks Mavs Nets Kings Hawks Lakers)

Suppose that we would like to get only the unique values from this array and store the results in a new array.

We can use the following syntax to do so:

uniques=($(echo "${my_array[@]}" | tr ' ' '\n' | sort -u | tr '\n' ' '))

echo "${uniques[@]}"

The following screenshot shows how to use this syntax in practice:

Bash get unique values from array

Notice that when we use the echo command to view the values in the uniques array we can see that it contains only the unique values from the original array:

  • Hawks
  • Kings
  • Lakers
  • Mavs
  • Nets

Feel free to use similar syntax to get the unique values from your own array in Bash.

Related Tutorials

The following tutorials explain how to perform other common tasks in Bash:

Bash: How to Iterate Over Associative Array
Bash: How to Remove Last Element from Array
Bash: How to Find Minimum and Maximum Values in Array

Leave a Reply