Skip to main content
2 of 5
quote argument to `unset`
U. Windl
  • 1.8k
  • 15
  • 33

According to TIMTOWDI (There Is More Than One Way To Do It), here is my solution, reversing array a into r:

#!/bin/bash
set -u
a=(1 2 3)
i=(${!a[@]})
declare -p a i
r=()
while [ ${#i[@]} -gt 0 ]
do
    r+=(${a[${i[-1]}]})
    unset 'i[-1]'
done
echo "${r[@]}"
declare -p r

When executing with BASH "4.4.23(1)-release (x86_64-suse-linux-gnu)" I got:

+ set -u
+ a=(1 2 3)
+ i=(${!a[@]})
+ declare -p a i
declare -a a=([0]="1" [1]="2" [2]="3")
declare -a i=([0]="0" [1]="1" [2]="2")
+ r=()
+ '[' 3 -gt 0 ']'
+ r+=(${a[${i[-1]}]})
+ unset 'i[-1]'
+ '[' 2 -gt 0 ']'
+ r+=(${a[${i[-1]}]})
+ unset 'i[-1]'
+ '[' 1 -gt 0 ']'
+ r+=(${a[${i[-1]}]})
+ unset 'i[-1]'
+ '[' 0 -gt 0 ']'
+ echo 3 2 1
3 2 1
+ declare -p r
declare -a r=([0]="3" [1]="2" [2]="1")
U. Windl
  • 1.8k
  • 15
  • 33