Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to reverse array in bash onliner FOR loop?

Tags:

bash

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.

like image 571
pedrosaurio Avatar asked Nov 13 '12 11:11

pedrosaurio


People also ask

How do you print an array in reverse?

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.


2 Answers

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 
like image 80
choroba Avatar answered Sep 30 '22 18:09

choroba


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 
like image 28
bereal Avatar answered Sep 30 '22 17:09

bereal