Unix & Linux Stack Exchange is a question and answer site for users of Linux, FreeBSD and other Un*x-like operating systems. It's 100% free, no registration required.

Sign up
Here's how it works:
  1. Anybody can ask a question
  2. Anybody can answer
  3. The best answers are voted up and rise to the top

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?

share|improve this question
3  
Also note that you basically never want "${array[*]}" instead of "${array[@]}". Using * instead of @ more or less treats it as a string instead of an array. – jordanm yesterday
up vote 3 down vote accepted

You can do this using indirection. From the bash manpage:

If the first character of parameter is an exclamation point (!), it introduces a level of variable indirection. Bash uses the value of the variable formed from the rest of parameter as the name of the variable; this variable is then expanded and that value is used in the rest of the substitution, rather than the value of parameter itself. This is known as indi‐ rect expansion. The exceptions to this are the expansions of ${!prefix*} and ${!name[@]} described below. The exclama‐ tion point must immediately follow the left brace in order to introduce indirection.

For your example:

#!/bin/bash
AR=('foo' 'bar' 'baz' 'bat')
for i in "${!AR[@]};" do
  printf '${AR[%s]}=%s\n' "$i" "${AR[i]}"
done

This results in:

${AR[0]}=foo
${AR[1]}=bar
${AR[2]}=baz
${AR[3]}=bat

Note that this also work for non-succesive indexes:

#!/bin/bash
AR=([3]='foo' [5]='bar' [25]='baz' [7]='bat')
for i in "${!AR[@]};" do
  printf '${AR[%s]}=%s\n' "$i" "${AR[i]}"
done

This results in:

${AR[3]}=foo
${AR[5]}=bar
${AR[7]}=bat
${AR[25]}=baz
share|improve this answer

Additional to jordanm's answer you can also do a C like loop in bash:

for ((idx=0; idx<${#array[@]}; ++idx)); do
    echo "$idx" "${array[idx]}"
done
share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.