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

https://t.co/AGeihMALAv configuring grub2 with EFI Fri Sep 13 05:20:01 +0000 2019

I published a Thing on @thingiverse! https://t.co/IYpRyEb7Hz #thingalert Tue Jul 23 19:27:57 +0000 2019

Nokogiri install on MacOSX https://t.co/v3An0miW9L Fri Jul 12 15:06:49 +0000 2019

HTML email with plain mailer plugin on Jenkins https://t.co/Z6FSDMDjy8 Thu Jul 11 21:07:25 +0000 2019

git sparse checkout within Jenkinsfile https://t.co/tcL7V8mzFK Thu Jul 11 20:40:53 +0000 2019