#!/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
#!/usr/bin/env zsh
tst() {
if cmpArrays $1 $2; then
result=match
else
result=nomatch
fi
if [[ $result == $3 ]]; then
print $1 $2 $3 pass
else
print $1 $2 $3 FAIL
fi
}
a1=(a b c)
a2=(a b c)
a3=(a b c d)
a4=('a b' c)
a5=(a c b)
a6=(a b '' c)
tst a1 a2 match
tst a1 a3 nomatch
tst a1 a4 nomatch
tst a1 a5 nomatch
tst a1 a6 nomatch
2条答案
按热度按时间hof1towb1#
下面是一个基本函数,它逐个元素地比较两个数组变量:
c8ib6hqw2#
如果你知道数组不会包含
null
(并且非常非常少的shell值有null
),你可以使用它作为分隔符来比较数组的连接版本:作为函数:
测试:
测试输出:
j
和P
标志在zsh
文档的参数扩展部分进行了说明。