Reputation: 840
I would like to set array elements with loop:
for i in 0 1 2 3 4 5 6 7 8 9
do
array[$i] = 'sg'
done
echo $array[0]
echo $array[1]
So it does not work. How to..?
Upvotes: 9
Views: 30926
Reputation: 3460
# Declare Array
NAMEOFSEARCHENGINE=( Google Yahoo Bing Blekko Rediff )
# get length of an array
arrayLength=${#NAMEOFSEARCHENGINE[@]}
# use for loop read all name of search engine
for (( i=0; i<${arrayLength}; i++ ));
do
echo ${NAMEOFSEARCHENGINE[$i]}
done
Output:
Google
Yahoo
Bing
Blekko
Rediff
Upvotes: 1
Reputation: 392929
My take on that loop:
array=( $(yes sg | head -n10) )
Or even simpler:
array=( sg sg sg sg sg sg sg sg sg sg )
See http://ideone.com/DsQOZ for some proof. Note also, bash 4+ readarray:
readarray array -t -n 10 < <(yes "whole lines in array" | head -n 10)
In fact, readarray is most versatile, e.g. get the top 10 PIDs of processes with bash in the name into array (which could return an array size<10 if there aren't 10 such processes):
readarray array -t -n 10 < <(pgrep -f bash)
Upvotes: 0
Reputation: 139
there is problem with your echo statement: give ${array[0]}
and ${array[1]}
Upvotes: 1
Reputation: 51603
It should work if you had declared your variable as array, and print it properly:
declare -a array
for i in 0 1 2 3 4 5 6 7 8 9
do
array[$i]="sg"
done
echo ${array[0]}
echo ${array[1]}
See it in action here.
HTH
Upvotes: 2
Reputation: 272487
Remove the spaces:
array[$i]='sg'
Also, you should access the elements as*:
echo ${array[0]}
See e.g. http://tldp.org/LDP/abs/html/arrays.html.
Upvotes: 7