如果没有你的数组元素包含一个换行符,你可以这样做:
mapfile -t uniq < <(printf "%s\n" "${RUN_Arr[@]}" | sort -u)
if ((${#uniq[@]} > 1)); then
echo "The elements are not the same: ${uniq[@]}"
# ...
如果需要防止用换行符元素,有一个简单的解决方案,如果您有bash的4.4(对该-d
选项)和GNU或FreeBSD排序(对于-z
选项):
mapfile -d '' -t uniq < <(printf "%s\n" "${RUN_Arr[@]}" | sort -zu)
if ((${#uniq[@]} > 1)); then
echo "The elements are not the same: ${uniq[@]}"
exit 1
fi
没有bash的4.4,你可以使用@ hunteke的回答改编:
for i in "${RUN_Arr[@]:1}"; do
if [[ $i != ${RUN_ARR[0]} ]]; then
printf "The elements are not the same:"
printf "%s\0" "${RUN_Arr[@]}" |
sort -zu |
xargs -0 printf " %s"
printf "\n"
exit 1
fi
done
(这仍然需要一种支持-z
。)
感谢您的回复,我想同样的做法。我想知道是否有一个函数获取数组中的唯一元素,如果是这样,我可以报告独特元素的数量是否超过一个。 –
本质上没有这样的功能,但这并不意味着你不能为自己写一个功能。我可能会使用Awk,外包给不同的语言,或Bash的散列表。看看[如何在Bash中定义哈希表?](https://stackoverflow.com/questions/1494178/how-to-define-hash-tables-in-bash) – hunteke