Parsing with read into an Array

Problem

You’ve got a varying number of words on each line of input, so you can’t just assign each word to a predetermined variable.

Solution

Use the -a option on the read statement, and the words will be read into an array variable.

read -a MYRAY

Discussion

Whether coming from user input or a pipeline, read will parse the input into words, putting each word in its own array element. The variable does not need to be declared as an array—using it in this fashion is enough to make it into an array. Each element can be referenced with the bash array syntax, which is a zero-based array. So the second word on a line of input will be put into ${MYRAY[1]} in our example. The number of words will determine the size of the array. In our example, the size of the array is ${#MYRAY[@]}.

Get bash Cookbook now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.