我试图在bash中找到整数数组中的最大值.我对bash很新.这是我到目前为止所拥有的......
max="${array[0]}"
for ((i=0;i<${#array[@]};i++))
do
if [ ${array[$i]} > $max ]
then
max="${array[$i]}"
fi
done
Run Code Online (Sandbox Code Playgroud)
其中数组大约是500个正整数.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
Run Code Online (Sandbox Code Playgroud)
或者,使用标准工具,尽管必须产生一些额外的进程,但这些工具可能会更快:
max=$( printf "%d\n" "${array[@]}" | sort -n | tail -1 )
Run Code Online (Sandbox Code Playgroud)