Search code examples
bashshell

Simple Way of Iterating over Indexes of Bash Special Array $@


When I create an array in bash, let's say,

ARR=(apple banana blueberry)

I can easily iterate over the indexes of $ARR by using ${!ARR[@]} to get the indexes, as in:

for i in ${!ARR[@]}; do
   echo "[$i]=${ARR[$i]}"
done

How do I do that to iterate over $@?

I first tried to get some "equivalence" with:

__fn(){ 
    for i in ${!@}; do
        echo "\[$i\]=${@\[$i\]}";
    done;
}

But I got "Bad Substitution" errors.

As a "workaround" I did a copy of the array with ARRAY=( "$@" ), but I'm looking for a more elegant way of doing that.

PS: Just to clarify, since it's been pointed that this question is similar to another: as you can see in the body of my question, it's not about how to access the nth element of an array or anything like that. I would like to iterate over indexes of $@.


Solution

  • How do I do that to iterate over ${@}?

    Usually eat arguments while iterating, for example when parsing options after getopt or getopts.

    while (($#)); do
       echo "$1"
       shift
    done
    

    If you want to loop non-destructively and have an index, I would:

    for ((i=1; i<=$#; ++i)); do
       echo "[$i]=${!i}"
    done
    

    If you are comfortable with arrays, just use an array:

    arr=("$@")
    

    But I got "Bad Substitution" errors.

    There is no such thing as ${@[$i]}. The ${!@} tries to do indirect expansion of the result of $@ and fails.

    I did a copy of the array with ARRAY=${@}

    ARRAY here is not assigned to be an array. ARRAY=${@} is a normal assignment, not an array.