Reputation: 34
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.
Upvotes: 1
Views: 175
Reputation: 22042
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[@]}"
ary
holds the values in the input order.sorted
holds the sorted result.Hope this helps.
Upvotes: 1
Reputation: 1688
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.
Upvotes: 1