[英]Bash comparing array value to find max
我正在嘗試在bash中的整數數組中找到最大值。 我是bash的新手。 這是我到目前為止所擁有的...
max="${array[0]}"
for ((i=0;i<${#array[@]};i++))
do
if [ ${array[$i]} > $max ]
then
max="${array[$i]}"
fi
done
其中數組大約為500個正整數ex。 24 27 13 34 2 104 645 411 1042 38 5 24 120 236 2 33 6
。 當前,它總是返回我數組中的最后一個整數。 似乎應該很容易解決,但是我不確定我缺少什么。 謝謝你的幫助。
此測試[ ${array[$i]} > $max ]
正在執行詞法比較,因此99大於100
您需要以下一種:
[[ ${array[$i]} -gt $max ]] # numeric comparison operator
(( ${array[$i]} > $max )) # arithmetic evaluation
或者,使用標准工具,盡管必須產生一些額外的過程,但它可能會更快:
max=$( printf "%d\n" "${array[@]}" | sort -n | tail -1 )
與其遍歷索引,不如遍歷項目本身。 更具體地針對您的實際問題,請確保您要進行算術比較,而不是字符串比較。
max="${array[0]}"
for i in "${array[@]}"; do
(( i > $max )) && max=$i
done
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.