4

I'm using bash to create a script outputting a set of values (one per line), then run it, and then put the output into an array. I want to retain the empty lines as empty array elements, because an empty value is still a value and it's the only way to match up to the list of values I was expecting back.

So for the following bash code:

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

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

The following alternatives didn't 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 this be done?

3
  • Does stackoverflow.com/questions/20776911/… help? Commented Mar 19, 2014 at 14:28
  • What version of bash? Commented Mar 19, 2014 at 15:03
  • I'm working on RHEL 6, so Bash 4.1. Commented Mar 20, 2014 at 2:11

1 Answer 1

7

If you are using bash 4 or later,

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

In earlier versions, I'd recommend a more piecemeal approach:

foo=()
while IFS= read -r; do
    foo+=( "$REPLY" )
done < <(echo 'foo bar'; echo; echo; echo baz)
Sign up to request clarification or add additional context in comments.

9 Comments

If I had a nickel for every time I forgot to use read -r cough hint cough... :-)
@chepner, is $REPLY a variable invoked by read automatically in cases where I do not specify a variable by myself? I would have done it like while read line; do...
@AdrianFrühwirth read -r is a more intentional oversight on my part :) but yes, I probably should include it.
@Ube Yes, REPLY is the default if you don't pass a name to read.
From help read: 'If no NAMEs are supplied, the line read is stored in the REPLY variable.' Off the top of my head, BASH_REMATCH and PIPE_STATUS are two arrays automatically populated under various circumstances, although neither is a default for a user-configurable option.
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.