Thomas Jung
Thomas Jung

Reputation: 33092

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

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

Upvotes: 12

Views: 18066

Answers (3)

Alberto Salvia Novella
Alberto Salvia Novella

Reputation: 1250

readarray -t ARRAY < <(COMMAND)

Upvotes: 4

SiegeX
SiegeX

Reputation: 140327

You need to change your Internal Field Separator variable (IFS) to a newline first.

$ IFS=$'\n'; arr=( $(echo -e "a b\nc\nd e") ); for i in ${arr[@]} ; do echo $i ; done
a b
c
d e

Upvotes: 16

jaypal singh
jaypal singh

Reputation: 77105

Set the IFS to newline. By default, it is space.

[jaypal:~] while IFS=$'\n' read -a arry; do 
echo ${arry[0]}; 
done < <(echo -e "a b\nc\nd e")
a b
c
d e

Upvotes: 0

Related Questions