18

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")'

3 Answers 3

40

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
Sign up to request clarification or add additional context in comments.

Comments

21

The simplest way to iterate seems to be:

#!/usr/bin/bash

array=(one two three)

# ${!array[@]} is the list of all the indexes set in the array
for i in ${!array[@]}; do
  echo "$i, ${array[$i]}"
done

Comments

1

Actually, for your shortest solution to answer exactly to the initial request, code should be :

#!/usr/bin/bash

array=(one two three)
for i in ${!array[@]}; do
  echo "$(($i+1)), ${array[$i]}"
done

... in order to print element number starting from 1, not zero.

$(($i+1)) is a Bash compound $(( )) command of "arithmetic expansion" for evaluation of arithmetic expressions.

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.