Howto use arrays in bash to store indexed information

Sometimes it's easier to write a quick script in bash that uses arrays rather than figure out how to do it with something more appropriate like awk or perl.

It's really very quick and simple. To start, declare your variable as an array


[uphill@host]: declare -a myvar

If the array is going to be global then add x to export it.


[uphill@host]: declare -ax myvar

Then you can put things into your array like this:


[uphill@host]: myvar[10]="hello there"
[uphill@host]: for x in `seq 1 9`
> do
> myvar[$x]=$((x*x))
> done

(this fills the first 9 indices with their squares and the 10th with "hello there")
Now to access elements of the array, you must encapsulate the entire variable and index
for myvar[10], this would be ${myvar[10]}


[uphill@zagreb]: for x in `seq 1 10`
> do
> echo $x:${myvar[$x]}
> done
1:1
2:4
3:9
4:16
5:25
6:36
7:49
8:64
9:81
10:hello there

Wordpress category: