Sign up ×
Unix & Linux Stack Exchange is a question and answer site for users of Linux, FreeBSD and other Un*x-like operating systems. It's 100% free, no registration required.

When I do,

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

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?

share|improve this question
'loop-device' is not related to a 'for loop'. Please consider removing the 'loop-device' tag. –  yeti Mar 26 '14 at 22:42
Do `echo "${ARRAY[$1]}" work? –  enedil Mar 26 '14 at 22:43
Could you please clarify? You are using $i as an iterator. When does it not work? –  terdon Mar 26 '14 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 '14 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 '14 at 22:55

1 Answer 1

up vote 3 down vote accepted

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 )) ;
     echo "Current Iterator i value:" $i
     echo "Array element at this position:" ${array[$i]}

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


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.

share|improve this answer
Yes, this example working.Thank you :) –  Guest Mar 26 '14 at 23:03
I believe you have an extra # in echo ${#array[$i]}. –  unxnut Mar 26 '14 at 23:18
@unxnut, Thanks for letting me know. Fixed the answer :) –  Ramesh Mar 26 '14 at 23:20

Your Answer


By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.