Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 894
Gábor Varga Avatar asked Dec 17 '11 16:12

Gábor Varga


People also ask

Are there arrays in shell script?

There are two types of arrays that we can work with, in shell scripts. The default array that's created is an indexed array. If you specify the index names, it becomes an associative array and the elements can be accessed using the index names instead of numbers.

What is array in bash script?

Arrays are important concepts in programming or scripting. Arrays allow us to store and retrieve elements in a list form which can be used for certain tasks. In bash, we also have arrays that help us in creating scripts in the command line for storing data in a list format.

Are there arrays in Bash?

Bash provides one-dimensional indexed and associative array variables. Any variable may be used as an indexed array; the declare builtin will explicitly declare an array. There is no maximum limit on the size of an array, nor any requirement that members be indexed or assigned contiguously.


3 Answers

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!
like image 66
Oliver Charlesworth Avatar answered Oct 06 '22 23:10

Oliver Charlesworth


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

like image 23
Zsolt Botykai Avatar answered Oct 07 '22 01:10

Zsolt Botykai


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

like image 34
harish.venkat Avatar answered Oct 06 '22 23:10

harish.venkat