脚本将读取 5 个数字,然后从最高到最低排序

脚本将读取 5 个数字,然后从最高到最低排序

我正在尝试创建一个脚本,该脚本将获取 5 个数字,然后将它们从最大到最小排序。到目前为止,这就是我所拥有的:

#!/bin/bash
clear

echo "********Sorting********"
echo "Enter first number:"
read n1
echo "Enter second number:"
read n2
echo "Enter third number:"
read n3
echo "Enter fourth number:"
read n4
echo "Enter fifth number:"
read n5  

答案1

您可以只使用带有反向开关的排序:

echo -e "$n1\n$n2\n$n3\n$n4\n$n5" | sort -rn 

答案2

对此任务进行编程的更好方法。

#!/bin/bash

# put number names into array
number_names_arr=(first second third fourth fifth)

# use loop, because code duplication is a bad practice. 
# It repeats five times all commands it have inside.
for ((i = 0; i < 5; i++)); do
    # Prompt line
    echo "Enter ${number_names_arr[i]} number"

    # read inputted number into array
    read -r numbers_arr[i]
done

echo "Output:"
# pass the content of array to the sort command
printf '%s\n' "${numbers_arr[@]}" | sort -rn 

答案3

这应该完成工作:

#!/usr/bin/env bash

array=("${@}")

while [[ "${1++}" ]]; do
  n=${1}
  <<< "${n}" grep -P -e '^(([+-]?)([0-9]+?)(\.?)(([0-9]+?)?))$' > '/dev/null' \
    || { echo "ERROR: '${n}' is not a number"; exit 1; }
  shift
done

printf '%s\n' "${array[@]}" | sort -rg

例子:

$ myscript.sh 12 -45 2 -27.75 2.2 0 +25 100 2.15
100
+25
12
2.2
2.15
2
0
-27.75
-45

相关内容