1

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

myscript.sh
#!/bin/bash
A=('foo' 'bar' 'baz' 'bat')
for i in ${A[*]}; do
  echo $i
done
Actual result
foo
bar
baz
bat
Desired result
0
1
2
3

How do I alter my script to achieve this?

1 Answer 1

3

You can loop over index using indirect reference syntax (since Bash 3) :

#!/bin/bash

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

For more : How to iterate over associative arrays in Bash

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.