How can I reverse the order in which I perform a for loop for a defined array
To iterate through the array I am doing this:
$ export MYARRAY=("one" "two" "three" "four") $ for i in ${MYARRAY[@]}; do echo $i;done one two three four
Is there a function where I can reverse the order of the array?
One thought I had is to generate a sequence of inverted indexes and call the elements by using this reversed index but maybe there is a quicker alternative, or at least easier to read.
To print an array in reverse order, we shall know the length of the array in advance. Then we can start an iteration from length value of array to zero and in each iteration we can print value of array index. This array index should be derived directly from iteration itself.
You can use the C-style for loop:
for (( idx=${#MYARRAY[@]}-1 ; idx>=0 ; idx-- )) ; do echo "${MYARRAY[idx]}" done
For an array with "holes", the number of elements ${#arr[@]}
doesn't correspond to the index of the last element. You can create another array of indices and walk it backwards in the same way:
#! /bin/bash arr[2]=a arr[7]=b echo ${#arr[@]} # only 2!! indices=( ${!arr[@]} ) for ((i=${#indices[@]} - 1; i >= 0; i--)) ; do echo "${arr[indices[i]]}" done
You can use tac, which is an opposite of cat
in sense that it reverses the lines.
MYARRAY=("one" "two" "three" "four") for item in "$MYARRAY"; do echo "$item"; done | tac # four # three # two # one
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With