[Code Example] Remove duplicate elements from array using bash script

Total
0
Shares

In this article we will provide you the bash script code to remove duplicate elements from array. In this approach, the order of list items may change.

Code Example –

#!/bin/bash

remove_array_duplicates() {
    declare -A tmp_array

    for i in "[email protected]"; do
        [[ $i ]] && IFS=" " tmp_array["${i:- }"]=1
    done

    printf '%s\n' "${!tmp_array[@]}"
}

arr=(we love nature we love animals)

remove_array_duplicates "${arr[@]}"

# Output:
# nature
# love
# we
# animals

Inspired from Dylan Araps

Live Demo

Demo might not work in private window (incognito)

Sign Up for Our Newsletters

Get only the best articles delivered to your mail

You May Also Like