Mowzer Mowzer - 7 months ago 19
Bash Question

Accessing array index variable from bash shell script loop?

I want to access the array index variable while looping thru an array in my bash shell script.

myscript.sh

#!/bin/bash
AR=('foo' 'bar' 'baz' 'bat')
for i in ${AR[*]}; do
echo $i
done


The result of the above script is:

foo
bar
baz
bat


The result I seek is:

0
1
2
3


How do I alter my script to achieve this?

Answer

You can loop over index using indirect reference syntax :

#!/bin/bash

AR=('foo' 'bar' 'baz' 'bat')
for i in ${!AR[*]}; do # replace ${AR[*]} with ${!AR[*]}
  echo $i
done