How Do You Use an Array in Linux (Bash)?

Problem scenario
You are aware that arrays are a supported data type in Bash. You would like to iterate through some variables as arrays could enable complex logic. What do you do?

The array is zero-based. So the first element is referred to by index number 0.

continualarray=(dog cat hamster rabbit horse cow)
echo ${continualarray[2]}
echo ${continualarray[5]}

Create a file foobar.txt to test an array's line-reading capacity.

$ cat /tmp/foobar.txt
this is a sentence
another sentence is here.
some more text.
various words; another phrase.

Here is an example of the built-in readarray command:

readarray rows < /tmp/foobar.txt
echo ${rows[2]) # this will print out this:
some more text.

Leave a comment

Your email address will not be published. Required fields are marked *