Bash

Deduplicate Array (preserve order)

admin by @admin ADMIN
1d ago
May 31, 2026
Public
0 0 up · 0 down Sign in to vote
Bash's associative arrays let you dedupe in a single pass while keeping the original order — `sort -u` would shuffle.
Bash
Raw
input=(apple banana apple cherry banana date apple)

dedupe() {
    declare -A seen=()
    local out=()
    for item in "$@"; do
        if [[ -z "${seen[$item]+x}" ]]; then
            seen[$item]=1
            out+=("$item")
        fi
    done
    printf '%s\n' "${out[@]}"
}

dedupe "${input[@]}"
# apple
# banana
# cherry
# date
Tags

Save your own code snippets

Create a free account and build your private vault. Share publicly whenever you want.