bash 在 Linux shell 脚本中,如何打印数组的最大值和最小值?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/13634429/
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
In Linux shell script how do i print the largest and smallest values of a array?
提问by BobbyT28
I dont really understand much about arrays but i need to know how to find and print the largest and smallest values of an array. The array is predefined by a read command, the user will be prompted to enter n amount of integers.
我不太了解数组,但我需要知道如何查找和打印数组的最大值和最小值。该数组由读取命令预定义,用户将被提示输入 n 个整数。
How would i assign the read input to an array and find and display the largest and smallest values of the array?
我如何将读取输入分配给数组并查找并显示数组的最大值和最小值?
Is there a way to test the array elements to see if they are all integers?
有没有办法测试数组元素以查看它们是否都是整数?
#!/bin/bash
read -a integers
biggest=${integers[0]}
smallest=${integers[0]}
for i in ${integers[@]}
do
if [[ $i -gt $biggest ]]
then
biggest="$i"
fi
if [[ $i -lt $smallest ]]
then
smallest="$i"
fi
done
echo "The largest number is $biggest"
echo "The smallest number is $smallest"
回答by sampson-chen
The general idea is to iterate through the array once and keep track of what the max
and min
seen so far at each step.
一般的想法是遍历数组一次并跟踪每一步到目前为止看到的max
和min
看到的内容。
Some comments and explanations in-line (prefixed by #
)
一些评论和解释(以 为前缀#
)
# This is how to declare / initialize an array:
arrayName=(1 2 3 4 5 6 7)
# Use choose first element of array as initial values for min/max;
# (Defensive programming) - this is a language-agnostic 'gotcha' when
# finding min/max ;)
max=${arrayName[0]}
min=${arrayName[0]}
# Loop through all elements in the array
for i in "${arrayName[@]}"
do
# Update max if applicable
if [[ "$i" -gt "$max" ]]; then
max="$i"
fi
# Update min if applicable
if [[ "$i" -lt "$min" ]]; then
min="$i"
fi
done
# Output results:
echo "Max is: $max"
echo "Min is: $min"
回答by Gilles Quenot
Try this if you need to compare(signed or not) INTegers:
如果您需要比较(签名与否)INTegers ,请尝试此操作:
#!/bin/bash
arr=( -10 1 2 3 4 5 )
min=0 max=0
for i in ${arr[@]}; do
(( $i > max || max == 0)) && max=$i
(( $i < min || min == 0)) && min=$i
done
echo "min=$min
max=$max"
OUTPUT
输出
min=-10
max=5
EXPLANATIONS
说明
arr=( )
is the declaration of the array((...))
is an arithmetic command, which returns an exit status of 0 if the expression is nonzero, or 1 if the expression is zero. Also used as a synonym for "let", if side effects (assignments) are needed. See http://mywiki.wooledge.org/ArithmeticExpression[[
is a bash keyword similar to (but more powerful than) the[
command. See http://mywiki.wooledge.org/BashFAQ/031and http://mywiki.wooledge.org/BashGuide/TestsAndConditionalsUnless you're writing for POSIX sh, we recommend[[
foo || bar
runs bar when foo fails:[[ -d $foo ]] || { echo 'ohNoes!' >&2; exit 1; }
cmd1 && cmd2
: cmd1 is executed, and then if its exit status was 0 (true), cmd2 is executed. See http://mywiki.wooledge.org/BashGuide/TestsAndConditionals
arr=( )
是数组的声明((...))
是一个算术命令,如果表达式不为零,则返回退出状态 0,如果表达式为零,则返回 1。如果需要副作用(赋值),也用作“let”的同义词。见http://mywiki.wooledge.org/ArithmeticExpression[[
是一个 bash 关键字,类似于(但比[
命令更强大)。请参阅http://mywiki.wooledge.org/BashFAQ/031和http://mywiki.wooledge.org/BashGuide/TestsAndConditionals除非您为 POSIX sh 编写,否则我们建议您[[
foo || bar
当 foo 失败时运行 bar:[[ -d $foo ]] || { echo 'ohNoes!' >&2; exit 1; }
cmd1 && cmd2
: cmd1 被执行,然后如果其退出状态为 0 (true),则 cmd2 被执行。请参阅http://mywiki.wooledge.org/BashGuide/TestsAndConditionals
回答by gniourf_gniourf
A funny way using sort:
使用排序的一种有趣方式:
if you have an array of integers, you can use sort
to sort it, then select the first and last elements to have the min and max elements, as in:
如果你有一个整数数组,你可以用sort
它来排序,然后选择第一个和最后一个元素来包含最小和最大元素,如下所示:
{ read min; max=$(tail -n1); } < <(printf "%s\n" "${array[@]}" | sort -n)
So if you want to prompt user for say 10 integers, check that the user entered integers and then sort them, you could do:
因此,如果您想提示用户输入 10 个整数,请检查用户是否输入了整数,然后对它们进行排序,您可以这样做:
#!/bin/bash
n=10
array=()
while ((n));do
read -p "[$n] Give me an integer: " i
[[ $i =~ ^[+-]?[[:digit:]]+$ ]] || continue
array+=($i)
((--n))
done
# Sort the array:
{ read min; max=$(tail -n1); } < <(printf "%s\n" "${array[@]}" | sort -n)
# print min and max elements:
echo "min=$min"
echo "max=$max"