bashvariable-assignment

How to read multiple lines into variables with a single read-command?


I need to read a three-line text like:

4
10
foo

into three variables: num1, num2, name.

I tried IFS=$'\n' read num1 num2 name <<< $data, but that only initializes the num1, leaving the rest of the variables empty.

Then I tried to overwrite the line-delimeter with read -d $'\0', but that just fails (with no error-message), and my script aborts (because I run with -e).

Can a multiline text be parsed/assigned to multiple variables in a single read?


Solution

  • Turns out, I was doing it right with the -d switch. However, read exits with code 1 when it encounters EOF. Documented behavior, explained here... (Makes sense, actually, as it allows you to loop over text with while read ... )

    Because I want the -e to catch all unexpected failures, I modified the parsing line to ignore the expected one: read -r -d '' num1 num2 name <<< $data || :, as suggested by @pjh in his comment, and now the script works properly.