Saving fields into arrays

Using the -a option to the read builtin, we can save the separated fields of a read line of input as an array variable, instead of a set of named string variables. This is particularly useful if we have a varying number of fields on each line:

$ cat animals-by-letter
alligator anteater armadillo
bee
caribou cat

elephant

Note that the fourth line in the preceding data is blank!

We can get an array of all the animals on each line, as separated by spaces, into an array named animals for each loop run, and then iterate over that array with a for loop; a loop within a loop:

#!/bin/bash
while read -r -a animals ; do
    for animal in "${animals[@]}" ; do
        printf '%s\n' "$animal"
    done
done < animals-by-letter

On running this code, we get a list of all of the animals, each terminated by a newline:

alligator
anteater
armadillo
bee
caribou
cat
elephant

Notice that the fourth line being empty meant that the animals array read for that line ended up empty, so the for loop never ran printf during that iteration of the while loop.