![스크립트는 5개의 숫자를 읽은 다음 가장 높은 숫자에서 가장 낮은 숫자로 정렬합니다.](https://linux55.com/image/115541/%EC%8A%A4%ED%81%AC%EB%A6%BD%ED%8A%B8%EB%8A%94%205%EA%B0%9C%EC%9D%98%20%EC%88%AB%EC%9E%90%EB%A5%BC%20%EC%9D%BD%EC%9D%80%20%EB%8B%A4%EC%9D%8C%20%EA%B0%80%EC%9E%A5%20%EB%86%92%EC%9D%80%20%EC%88%AB%EC%9E%90%EC%97%90%EC%84%9C%20%EA%B0%80%EC%9E%A5%20%EB%82%AE%EC%9D%80%20%EC%88%AB%EC%9E%90%EB%A1%9C%20%EC%A0%95%EB%A0%AC%ED%95%A9%EB%8B%88%EB%8B%A4..png)
저는 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