Shell Bash script to print numbers in ascending order
I am really new to shell Bash scripting. I need to print numbers in ascending order along the line for a given arbitrary number that is entered 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
+3
source to share
3 answers
You can use this script:
#!/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=' '
makeread
all number delimited by space - 'read -ra` to read all numbers in the array
-
sort -n
to sort numbers numerically -
printf "%s\n" "${arr[@]}"
to print each element of the array on a separate line -
<(printf "%s\n" "${arr[@]}")
is a process substitution that makes a commandprintf
behave like a file for the commandsort -n
.
+4
source to share
Ask the user to enter an input with a comma and parse it and then populate the array nos
.
echo "Please enter numbers separated by comma: "
read string_var
IFS=',' read -a nos <<< "$string_var"
Or in terms of space it is simpler:
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 ....
+1
source to share
Bashisms using bash
If you
- want to use bash (no fork and no external binaries)
- use small gateway numbers (less than 2 ^ 60, aka: <2305843009213693952)
- do not have duplicate numbers
Under 64 bit bash, you can use an array index to store and sort an integer:
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
To eliminate the duplicate:
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
+1
source to share