我是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
答案 0 :(得分:4)
您可以使用此脚本:
#!/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
所有以空格分隔的数字sort -n
以数字方式对数字进行排序printf "%s\n" "${arr[@]}"
以单独的行<(printf "%s\n" "${arr[@]}")
是进程替换,使printf
命令的行为类似于sort -n
命令的文件。答案 1 :(得分:1)
要求用户用逗号输入并解析它,然后填充nos
数组..
echo "Please enter numbers separated by comma: "
read string_var
IFS=',' read -a nos <<< "$string_var"
或者通过太空更容易:
echo "Please enter numbers separated by space: "
read string_var
nos=($string_var) //now you can access it like array...
// now rest of the code ....
答案 2 :(得分:1)
如果你
在64位bash下,您可以使用数组索引来存储和排序整数:
read -a array <<<'4 -1 2 66 10'
for i in ${array[@]};do
sorted[i+(2<<60)]=''
done
for i in ${!sorted[@]};do
echo $[i-(2<<60)]
done
-1
2
4
10
66
read -a arr <<<'4 -1 2 66 -12 -10 10 2 24 -10'
for i in ${arr[@]};do
((srtd[i+(2<<60)]++))
done
for i in ${!srtd[@]};do
for ((l=0;l<${srtd[i]};l++));do
echo $[i-(2<<60)]
done
done
-12
-10
-10
-1
2
2
4
10
24
66