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.