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?
Unix & Linux Stack Exchange is a question and answer site for users of Linux, FreeBSD and other Un*x-like operating systems. It only takes a minute to sign up.
Sign up to join this communityTry 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.
$i
as an iterator. When does it not work?$1
relevant? Show the code that does not work and explain what you expected to get and what you actually get.