9

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..?

3
  • 1
    Do you know the seq command? you could replace your numbers with $(seq 0 9) Commented Dec 17, 2011 at 16:06
  • You need to be careful, as some shells do not have arrays. If you want to writable portable sh, you cannot use arrays at all. Commented Dec 17, 2011 at 16:49
  • Definitely a bashism, I've fixed the tags. Commented Dec 18, 2011 at 19:36

5 Answers 5

7

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!

Sign up to request clarification or add additional context in comments.

Comments

2

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

Comments

1

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

Comments

1
# 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

Comments

0

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)

1 Comment

added readarray, which has it's place for allowing embedded whitespace easily

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.