September 2018
Beginner
186 pages
4h 30m
English
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 ...
Read now
Unlock full access