13

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
2
  • possible duplicate of How do I create an array in bash from a command variable? Commented Jan 7, 2012 at 14:31
  • Someone might be able to find a better duplicate; that's just the most recent one. This question has probably been asked dozens of times. Commented Jan 7, 2012 at 14:32

3 Answers 3

17

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
Sign up to request clarification or add additional context in comments.

2 Comments

Thanks for the explanations. I'm wondering why you use echo -e and not just echo. Any reason?
the -e flag tells echo to interpret backslash escape characters such as \n to output a newline vs a literal \n
4
readarray -t ARRAY < <(COMMAND)

Comments

0

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

1 Comment

No, by default it is $' \t\n', spaces tabs and newlines.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.