Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Capture multiline output as array in bash [duplicate]

Tags:

bash

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?

like image 595
djechlin Avatar asked Dec 11 '12 15:12

djechlin


1 Answers

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.
like image 63
sampson-chen Avatar answered Sep 25 '22 00:09

sampson-chen