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[@]}.
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Read now
Unlock full access