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

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

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

Separates the input for each new line and space 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 ab c de 
+7
source share
2 answers

You need to first change the internal field separator ( IFS ) variable to the first line.

 $ IFS=$'\n'; arr=( $(echo -e "ab\nc\nd e") ); for i in ${arr[@]} ; do echo $i ; done ab c de 
+13
source

Set IFS to newline . The default is space .

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

All Articles