How to save blank lines when reading a command in a bash array?

I use bash to create a script to output a set of values ​​(one per line), then run it, and then put the output in an array. I want to save empty strings as empty array elements, because an empty value is still a value, and this is the only way to match the list of values ​​that I expected.

So, for the following bash code:

> IFS=$'\n'
> foo=( $(echo 'foo bar'; echo; echo; echo baz) )
> echo ${#foo[@]}
2

I expected to see 4 outputs because there were four lines of output. Instead, only rows with something on them are included, so there are only two values ​​in the array.

The following alternatives did not help:

> foo=( `echo 'foo bar'; echo; echo; echo baz` )
> echo ${#foo[@]}
2
> foo=( "$(echo 'foo bar'; echo; echo; echo baz)" )
> echo ${#foo[@]}
1

How can I do that?

+4
source share
1 answer

bash 4 ,

readarray -t foo < <(echo 'foo bar'; echo; echo; echo baz)

:

foo=()
while IFS= read -r; do
    foo+=( "$REPLY" )
done < <(echo 'foo bar'; echo; echo; echo baz)
+5

Source: https://habr.com/ru/post/1532481/


All Articles