2017-10-19 204 views
1

我有一个bash数组“RUN_Arr”,其值如下所示。如果值相同,我希望脚本继续,否则我想报告它们。检查bash数组值是否都相同

echo "${RUN_Arr[@]}" 
"AHVY37BCXY" "AHVY37BCXY" "AHVY37BCXY" "AHVY38BCXY" "AHVY37BCXY" "AHVY37BCXY" 

基于上述阵列上,我想回应:

No the array values are not same 
"AHVY37BCXY" "AHVY38BCXY" 

有人能提出一个解决办法?谢谢。

回答

5

迭代通过您的数组,并测试针对水印

arr=(a a a b a a a) 

watermark=${arr[0]} 
for i in "${arr[@]}"; do 
    if [[ "$watermark" != "$i" ]]; then 
     not_equal=true 
     break 
    fi 
done 

[[ -n "$not_equal" ]] && echo "They are not equal ..." 

非常简单的证明了概念你;显然会根据你的目的硬化。

+0

感谢您的回复,我想同样的做法。我想知道是否有一个函数获取数组中的唯一元素,如果是这样,我可以报告独特元素的数量是否超过一个。 –

+0

本质上没有这样的功能,但这并不意味着你不能为自己写一个功能。我可能会使用Awk,外包给不同的语言,或Bash的散列表。看看[如何在Bash中定义哈希表?](https://stackoverflow.com/questions/1494178/how-to-define-hash-tables-in-bash) – hunteke

2

如果没有你的数组元素包含一个换行符,你可以这样做:

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。)

+0

感谢Rici,这是非常有帮助的。 –