1

I have an array which I would like to iterate through in reverse order from start index to end index. This is what I tried

limits=( 10 20 26 39 48 )

echo "forward"
for i in ${limits[@]:0:4}; do
    echo "$i"
done

echo ""
echo "reverse"
for i in ${limits[@]:4:0}; do
    echo "$i"
done
1

1 Answer 1

2

In bash, the indices of an array do not have to be contiguous:

$ limits=( 10 20 26 39 48 )
$ declare -p limits
declare -a limits=([0]="10" [1]="20" [2]="26" [3]="39" [4]="48")

but:

$ a[10]=x
$ a[20]=y
$ b=(p q r s t)
$ unset b[3]
$ declare -p a b
declare -a a=([10]="x" [20]="y")
declare -a b=([0]="p" [1]="q" [2]="r" [4]="t")

The naïve approach of counting the number of elements and looping from max to min should work on simple arrays but may fail on arrays that have been created piece-meal or had elements removed.

However, you can convert the indices to a contiguous range by defining a function and assigning the elements of the array as its parameters. Here's an example that also passes in the name of a command/function to run:

$ applyInReverse(){
    local func=$1
    shift

    local i
    for ((i=$#; i>0; --i)); do
        "$func" "${@:i:1}"
    done
}

then invoking with echo gives:

$ applyInReverse echo "${limits[@]}"
48
39
26
20
10
$ applyInReverse echo "${b[@]}"
t
r
q
p
$
Sign up to request clarification or add additional context in comments.

2 Comments

I just spotted: stackoverflow.com/questions/13360091/… which shows an approach that generates a list from the array indices, then walks that backwards
@Cyrus thanks. specifically, mywiki.wooledge.org/BashFAQ/118?highlight=%28BASH_ARGV%29 linked from there seems to collect most of the approaches

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.