bash 如何在数组中找到最高的数字?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/12744245/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-09 22:48:03  来源:igfitidea点击:

How to find the highest number in an array?

bash

提问by Charlie

Possible Duplicate:
How to sort an array in BASH

可能的重复:
如何在 BASH 中对数组进行排序

I have numbers in the array 10 30 44 44 69 12 11.... How to display the highest from array?

我在数组中有数字10 30 44 44 69 12 11...。如何显示数组中的最高值?

echo $NUM //result 69

回答by choroba

You can use sortto find out.

您可以使用sort来了解一下。

#! /bin/bash
ar=(10 30 44 44 69 12 11)
IFS=$'\n'
echo "${ar[*]}" | sort -nr | head -n1

Alternatively, search for the maximum yourself:

或者,自己搜索最大值:

max=${ar[0]}
for n in "${ar[@]}" ; do
    ((n > max)) && max=$n
done
echo $max

回答by Charlie

try this:

尝试这个:

a=(10 30 44 44 69 12 11 100)

max=0
for v in ${a[@]}; do
    if (( $v > $max )); then max=$v; fi; 
done
echo $max

result in 100

结果是 100