1

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?

1 Answer 1

2

Add one character:

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

(Add an exclamation mark (!) to the array expansion: ${!AR[*]}.)  From the man page:

Parameter Expansion

           ︙
    ${!name[@]}
    ${!name[*]}
      List of array keys.  If name is an array variable, expands to the list of array indices (keys) assigned in name.  If name is not an array, expands to 0 if name is set and null otherwise.  When @ is used and the expansion appears within double quotes, each key expands to a separate word.

You must log in to answer this question.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.