Bash - reverse an array

Unconventional approach (all not pure bash):

  • if all elements in an array are just one characters (like in the question) you can use rev:

    echo "${array[@]}" | rev
    
  • otherwise:

    printf '%s\n' "${array[@]}" | tac | tr '\n' ' '; echo
    
  • and if you can use zsh:

    echo ${(Oa)array}
    

Another unconventional approach:

#!/bin/bash

array=(1 2 3 4 5 6 7)

f() { array=("${BASH_ARGV[@]}"); }

shopt -s extdebug
f "${array[@]}"
shopt -u extdebug

echo "${array[@]}"

Output:

7 6 5 4 3 2 1

If extdebug is enabled, array BASH_ARGV contains in a function all positional parameters in reverse order.


I have answered the question as written, and this code reverses the array. (Printing the elements in reverse order without reversing the array is just a for loop counting down from the last element to zero.) This is a standard "swap first and last" algorithm.

array=(1 2 3 4 5 6 7)

min=0
max=$(( ${#array[@]} -1 ))

while [[ min -lt max ]]
do
    # Swap current first and last elements
    x="${array[$min]}"
    array[$min]="${array[$max]}"
    array[$max]="$x"

    # Move closer
    (( min++, max-- ))
done

echo "${array[@]}"

It works for arrays of odd and even length.