I have an array called colNums that looks like this:


When I print the array with echo "$colNums" it prints like that. I want this list sorted.

I'm trying

    sortedColNums=($(for i in "${colNums[@]}"; do echo $i; done | sort -n))

but for some reason sortedNumCols only contains the first number, 1. Can anyone help?

EDIT: It turned out I had a string rather than an array. I got it into a sorted string with the second answer here: https://stackoverflow.com/questions/2625976/sorting-space-delimited-numbers-with-linux-bash

closed as off-topic by Michael Homer, Anthon, terdon Apr 12 '15 at 8:42

This question appears to be off-topic. The users who voted to close gave this specific reason:

  • "Questions describing a problem that can't be reproduced and seemingly went away on its own (or went away when a typo was fixed) are off-topic as they are unlikely to help future readers." – Michael Homer, terdon
If this question can be reworded to fit the rules in the help center, please edit the question.

  • Works fine for me. Can you provide some actual runnable code that exhibits the issue you're having? – Michael Homer Apr 12 '15 at 7:28
  • 2
    Actually, wait, echo "$colNums" can't possibly print like that if colNums is an array. You have a string with newlines in it. – Michael Homer Apr 12 '15 at 7:29
  • Whoops, thanks. Do you know how I can break it into an array? – Rio Apr 12 '15 at 7:32
  • 1
    Add output of declare -p colNums to your question. – Cyrus Apr 12 '15 at 7:32
  • colNums=($colNums) – Michael Homer Apr 12 '15 at 7:32

This works for me:

sortedColNums=( $( printf "%s\n" "${colNums[@]}" | sort -n ) )

Not the answer you're looking for? Browse other questions tagged or ask your own question.