2

When I do,

for ((i=0; i<"${ARRAY}"; i+=2))
do
    echo $i
    echo ${ARRAY[$i]}
done

echo $i works as I expected, also echo ${ARRAY[0]} works, but with $i as iterator i see only blank lines. How to write the for loop correctly?

7
  • 'loop-device' is not related to a 'for loop'. Please consider removing the 'loop-device' tag.
    – user62916
    Mar 26, 2014 at 22:42
  • Do `echo "${ARRAY[$1]}" work?
    – enedil
    Mar 26, 2014 at 22:43
  • Could you please clarify? You are using $i as an iterator. When does it not work?
    – terdon
    Mar 26, 2014 at 22:52
  • ${ARRAY[$1]} not working for me. clarify? When i'm using $i in ${ARRAY[$i]} echo prints blank line. When i'm using number (0, 1, 2, 3...) ${ARRAY[3]} it's working.
    – Guest
    Mar 26, 2014 at 22:53
  • Please edit your question, how is $1 relevant? Show the code that does not work and explain what you expected to get and what you actually get.
    – terdon
    Mar 26, 2014 at 22:55

1 Answer 1

3

Try the below script. It should work.

declare -a array=('1' '2' '3' '4' '5' '6' '7' '8' '9' '10' '11')
for ((i=0; i<=${#array[@]}; i+=2 )) ;
  do
     echo "Current Iterator i value:" $i
     echo "Array element at this position:" ${array[$i]}
 done

Output of the script

Current Iterator i value: 0
Array element at this position: 1
Current Iterator i value: 2
Array element at this position: 3
Current Iterator i value: 4
Array element at this position: 5
Current Iterator i value: 6
Array element at this position: 7
Current Iterator i value: 8
Array element at this position: 9
Current Iterator i value: 10
Array element at this position: 11

Explanation

I have initially declared an array with 11 elements.

From your question, I believe you are trying to iterate through all the elements available in the array.

${#array[@]} - This is used to determine the length of the array.

${array[$i]} - This is used to print an element at a particular index.

2
  • I believe you have an extra # in echo ${#array[$i]}.
    – unxnut
    Mar 26, 2014 at 23:18
  • @unxnut, Thanks for letting me know. Fixed the answer :)
    – Ramesh
    Mar 26, 2014 at 23:20

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .