Shell Bash脚本以升序打印数字 [英] Shell Bash script to print numbers in ascending order

查看:55
本文介绍了Shell Bash脚本以升序打印数字的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I am really new to shell Bash scripting. I need to print numbers in ascending order on a line for a given arbitrary number that is input by the user.

#!/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

推荐答案

您可以使用以下脚本:

#!/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

  • IFS =''使 read 的所有数字都由空格分隔
  • 'read -ra`读取数组中的所有数字
  • sort -n 对数字进行数字排序
  • printf%s \ n""$ {arr [@]}" 可以在单独的行中打印数组的每个元素
  • <(printf%s \ n""$ {arr [@]}")是进程替换,使 printf 命令的行为类似于 sort -n 命令.
    • IFS=' ' to make read all number delimited by space
    • 'read -ra` to read all numbers in an array
    • sort -n to sort numbers numerically
    • printf "%s\n" "${arr[@]}" to print each element of array in separate line
    • <(printf "%s\n" "${arr[@]}") is process substitution that make it printf command behave like a file for sort -n command.
    • 这篇关于Shell Bash脚本以升序打印数字的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆