bash + for loop + output index number and element bash + for loop + output index number and element bash bash

bash + for loop + output index number and element


You can iterate over the indices of the array, i.e. from 0 to ${#array[@]} - 1.

#!/usr/bin/basharray=(one two three)# ${#array[@]} is the number of elements in the arrayfor ((i = 0; i < ${#array[@]}; ++i)); do    # bash arrays are 0-indexed    position=$(( $i + 1 ))    echo "$position,${array[$i]}"done

Output

1,one2,two3,three


The simplest way to iterate seems to be:

#!/usr/bin/basharray=(one two three)# ${!array[@]} is the list of all the indexes set in the arrayfor i in ${!array[@]}; do  echo "$i, ${array[$i]}"done