在Linux shell脚本中,如何打印数组的最大值和最小值?

Bob*_*T28 4 bash sh

我真的不太了解数组,但我需要知道如何查找和打印数组的最大和最小值.该数组由读命令预定义,将提示用户输入n个整数.

如何将读取输入分配给数组并查找并显示数组的最大值和最小值?

有没有办法测试数组元素,看看它们是否都是整数?

#!/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"
Run Code Online (Sandbox Code Playgroud)

sam*_*hen 9

总的想法是通过阵列一次迭代和跟踪什么maxmin看到的迄今为止的每一步.

一些评论和解释在线(前缀#)

# 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"
Run Code Online (Sandbox Code Playgroud)


Gil*_*not 6

如果你需要比较(签名或不签名)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"
Run Code Online (Sandbox Code Playgroud)

OUTPUT

min=-10
max=5
Run Code Online (Sandbox Code Playgroud)

说明