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


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 –


remove_array_duplicates() {
    declare -A tmp_array

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

    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