arraysbashprintf

bash + for loop + output index number and element


This is my array:

$ ARRAY=(one two three)

How do I print the array so I have the output like: index i, element[i] using the printf or for loop I use below

1,one
2,two
3,three

Some notes for my reference

1 way to print the array:

$ printf "%s\n" "${ARRAY[*]}"
one two three

2 way to print the array

$ printf "%s\n" "${ARRAY[@]}"
one
two
three

3 way to print the array

$ for elem in "${ARRAY[@]}"; do  echo "$elem"; done
one
two
three

4 way to print the array

$ for elem in "${ARRAY[*]}"; do  echo "$elem"; done
one two three

A nothe way to look at the array

$ declare -p ARRAY
declare -a ARRAY='([0]="one" [1]="two" [2]="three")'

Solution

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

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

    Output

    1,one
    2,two
    3,three