Gábor Varga
Gábor Varga

Reputation: 840

Shell script arrays

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

Answers (5)

Praveen Kumar Verma
Praveen Kumar Verma

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

sehe
sehe

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

harish.venkat
harish.venkat

Reputation: 139

there is problem with your echo statement: give ${array[0]} and ${array[1]}

Upvotes: 1

Zsolt Botykai
Zsolt Botykai

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

Oliver Charlesworth
Oliver Charlesworth

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.


* Thanks to @Mat for reminding me of this!

Upvotes: 7

Related Questions