Capture multiline output as array in bash

bash

Solution

Try this:

var=($(./inner.sh))

# And then test the array with:

echo ${var[0]}
echo ${var[1]}
echo ${var[2]}

Output:

first
second
third

Explanation:

- You can make an array in bash by doing `var=(first second third)`, for example.

- `$(./inner.sh)` runs the `inner.sh` script, which prints out `first`, `second`, and `third` on separate lines. Since we don't didn't put double quotes around `$(...)`, they get lumped onto the same line, but separated by spaces, so you end up with what it looks like in the previous bullet point.

Problem

If `inner.sh` is ``` #... echo first echo second echo third ``` And `outer.sh` is ``` var=`./inner.sh` # only wants to use "first"... ``` How can `var` be split by whitespace?

Original source

Related problems