Shell Bash脚本以升序打印数字

CLe*_*ner 3 linux bash shell

我真的是Shell Bash脚本的新手。对于用户输入的给定任意数字,我需要在一行上按升序打印数字。

#!/bin/bash

declare nos[5]=(4 -1 2 66 10)
# Prints the number befor sorting

echo "Original Numbers in array:"
for (( i = 0; i <= 4; i++ ))
    do
      echo ${nos[$i]}
    done

 #
 # Now do the Sorting of numbers  
 #

for (( i = 0; i <= 4 ; i++ ))
do
   for (( j = $i; j <= 4; j++ ))
   do
      if [ ${nos[$i]} -gt ${nos[$j]}  ]; then
       t=${nos[$i]}
       nos[$i]=${nos[$j]}
       nos[$j]=$t
      fi
   done
done

#
# Print the sorted number
# 
echo -e "\nSorted Numbers in Ascending Order:"
for (( i=0; i <= 4; i++ )) 
do
  echo ${nos[$i]}
done
Run Code Online (Sandbox Code Playgroud)

anu*_*ava 5

您可以使用以下脚本:

#!/bin/bash
IFS=' ' read -ra arr -p "Enter numbers: "
Enter numbers: 4 -1 2 66 10

sort -n <(printf "%s\n" "${arr[@]}")
-1
2
4
10
66
Run Code Online (Sandbox Code Playgroud)
  • IFS=' '使read所有数字都由空格分隔
  • 'read -ra`读取数组中的所有数字
  • sort -n 对数字进行数字排序
  • printf "%s\n" "${arr[@]}" 在单独的行中打印数组的每个元素
  • <(printf "%s\n" "${arr[@]}")是进程替代,使它的printf命令行为像sort -n命令文件一样。