How to reverse array in bash onliner FOR loop?

bash

Solution

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

Problem

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.

Original source