Search code examples
shellzsh

How to test whether 2 arrays contain the same elements in zsh / Unix shell?


What is the right way to test whether 2 zsh arrays are structurally equal, i.e., contain the same elements?

[[ $array1 == $array2 ]] passes a few tests but I don't know whether it's the correct form and I can't seem to find the topic discussed anywhere.

I'm writing zsh code at the moment but I'm also interested in a portable answer (bash/POSIX) if different.


Solution

  • Here's a basic function that compares two array variables element by element:

    #!/usr/bin/env zsh
    
    # Takes the names of two array variables
    arrayeq() {
        typeset -i i len
    
        # The P parameter expansion flag treats the parameter as a name of a
        # variable to use
        len=${#${(P)1}} 
    
        if [[ $len -ne ${#${(P)2}} ]]; then
           return 1
        fi
    
        # Remember zsh arrays are 1-indexed
        for (( i = 1; i <= $len; i++)); do
            if [[ ${(P)1[i]} != ${(P)2[i]} ]]; then
                return 1
            fi
        done
    }
    
    arr1=(1 apple 3 4)
    arr2=(1 apple 4 5)
    
    if arrayeq arr1 arr2; then
        print They match
    else
        print They are different
    fi