Shell Bash script to print numbers in ascending order
bash, linux, shell
Solution
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=' '` 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.
Problem
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 ```