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
10:hello there

About the Author...

Slides from LISA 2019 Linux systems troubleshooting #LISA2019 Tue Oct 29 05:59:30 +0000 2019 configuring grub2 with EFI Fri Sep 13 05:20:01 +0000 2019

I published a Thing on @thingiverse! #thingalert Tue Jul 23 19:27:57 +0000 2019

Nokogiri install on MacOSX Fri Jul 12 15:06:49 +0000 2019

HTML email with plain mailer plugin on Jenkins Thu Jul 11 21:07:25 +0000 2019