1

I've been trying to read numeric input from the terminal in Bash (Two separate approaches. First is directly entering numbers into the CLI and second reading the numbers from a file) and saving it in an array, sorting the array and showing the result. (The original problem stated that the input is saved in an array and then sorted)

I don't know if it's better to save it in a file and sort the values in the file or directly the input from the terminal into the array and sorting it afterwards. I have searched for both methods.

Thank you.

P.S. I've read many sources and links but unfortunately I couldn't come across a solution. I've tried using loops and prompting the user in asking how many numbers they want to feed in as the input but it was doomed to failure.

2 Answers 2

1

Where does the input come from? Someone entering numbers, or a file, another process?

Either way, you seem to expect a finite number of inputs which then need sorting. Just pipe your inputs into sort -n (-n is for numeric sort). No need to use an intermediate array.

# Print some numbers on the console, pipe into sort.
cat <<-EOF | sort -n
1
3
2
EOF

If your inputs are coming from a file:

# Create FILE holding unsorted numbers.
$ cat <<-EOF > FILE 
1
3
2
EOF

# Sort contents of FILE.
$ cat FILE | sort -n
1
2
3

If you could be more specific, it would be easier to help.

Sign up to request clarification or add additional context in comments.

1 Comment

You are right. I'll edit the question. There wasn't really a strict recommendation in how to approach this problem. But I tried both ways. Reading from user input within the terminal itself and reading from a file and sorting the values inside.
1

Would you try the following:

if [[ -t 0 ]]; then
    # This line is executed when input from the terminal.
    echo "Input a numeric value and enter then continue. Enter a blank line when done."
fi

while read -r n; do
    [[ -z $n ]] && break    # exits the loop if the input is empty
    ary+=("$n")
done

sorted=($(sort -n < <(printf "%s\n" "${ary[@]}")))
printf "%s\n" "${sorted[@]}"
  • It accepts both user's input from the terminal and redirection from a file.
  • It expects the input to be a list of values separated by newlines.
  • When typing on the terminal, a user can complete the input by entering a blank line or pressing Ctrl+D.
  • The array ary holds the values in the input order.
  • The array sorted holds the sorted result.
  • The script does not check the validity of the input values. It may be better to examine if the input is a valid numeric value depending on the application.

Hope this helps.

1 Comment

What an elegant and nice solution! Thank you

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.