简体   繁体   中英

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
0
1
2
3
Actual result
 foo bar baz bat 
Desired result
 0 1 2 3 

How do I alter my script to achieve this?

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM