Following are two arrays of strings
arr1=("aa" "bb" "cc" "dd" "ee")
echo ${#arr1[@]} //output => 5
arr2=("cc" "dd" "ee" "ff")
echo ${#arr2[@]} //output => 4
The difference of the two arrays is arr_diff=("aa" "bb" "ff")
I can get the difference using the following and other methods from stackoverflow
arr_diff=$(echo ${arr1[@]} ${arr2[@]} | tr ' ' '\n' | sort | uniq -u)
OR
arr_diff=$(echo ${arr1[@]} ${arr2[@]} | xargs -n1 | sort | uniq -u)
echo ${arr_diff[@]} //output => (aa bb ff)
The point is not printing out the difference of the arrays, but getting the size of the difference array, so that I can validate if the two arrays have the same elements or not. However, if I try to query the size of the difference array, I get wrong answer.
echo ${#arr_diff[@]} //output => 1
I always get output as 1 irrespective of size of difference array (even when size is zero, i.e. both arr1 and arr2 have the same elements)
arr_diffis a plain variable, not an array at all. If you try to treat it as an array, it essentially functions like an array with just a single element (which might be any of "0", "1", "2", etc). So, to the extent that the number of elements in it is defined, it's always going to be 1. What did you expect it to be?readarray -t diff_items < <(comm -3 <(printf '%s\n' "${arr1[@]}" | sort -u) <(printf '%s\n' "${arr2[@]}" | sort -u))will do the right thing as long as none of your array elements contain newlines. (Note that some of the entries indiff_itemswill have whitespace prepended; this indicates whether the item was only in arr1 or only in arr2).