0

I've been searching many ways to sort the associative array by keys, and all of them need to echo the key & values in order to store them. But what I'm trying is just to sort them, and after all when we print out the array, the array prints out the correct order.

array=(0 4 6 1)
tmp=$(
   for ((i = 0; i < ${#array[@]}; ++i)); do
       echo "$i ${array[i]}" # Can we just store the value without echoing??
   done | sort | cut -d' ' -f1
)
readarray -t newArray <<<"$tmp"
declare -p newArray

This works well, but I kind of want to try without echoing the key and values so that later on when I do echo ${newArray[@]}, it prints out 0 1 2 3. It's kind of unnecessary but I'm just wondering since I'm a newbie to shall scripting.

Chocode
  • 147
  • 9
  • 2
    You have to echo if you want to send it to the next command in the pipeline, since pipelines work with output. – Barmar Feb 18 '22 at 01:53
  • 1
    Nothing in that code uses an associative array. – rici Feb 18 '22 at 02:19
  • if you want to maintain the current array, and you don't want to use the `echo` command, consider copying the current array to the new array and then sort the new array in place; something like a simple bubble sort (not very efficient, especially in bash, but relatively easy enough to code from a newbie perspective) – markp-fuso Feb 18 '22 at 03:23
  • I approved the duplicate nomination, since you seem to _actually_ be asking how to sort an array. If you really wanted to ask a different question, please [edit] this and it will be submitted to a queue for possible reopening. – tripleee Feb 18 '22 at 05:51

0 Answers0