Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to convert command output to an array line by line in bash?

Tags:

arrays

bash

shell

I'm trying to convert the output of a command like echo -e "a b\nc\nd e" to an array.

X=( $(echo -e "a b\nc\nd e") )

Splits the input for every new line and whitespace character:

$ echo ${#X[@]}
> 5

for i in ${X[@]} ; do echo $i ; done
a
b
c
d
e

The result should be:

for i in ${X[@]} ; do echo $i ; done
a b
c
d e
like image 883
Thomas Jung Avatar asked Jan 07 '12 08:01

Thomas Jung


1 Answers

readarray -t ARRAY < <(COMMAND)
like image 100
Alberto Salvia Novella Avatar answered Oct 09 '22 15:10

Alberto Salvia Novella