Situation: I have to store a commands output in an array with each line being one element. These lines may contain whitespaces which seems to screw with everyting.
Normally I would do something like ARRAY=($(command)). However if I try doing something like ARRAY=($(printf '%s\n' "first line" "second line")) the array will look like this
$ for x in "${ARRAY[@]}"; do echo $x; done
first
line
second
line
I have found a way to achieve the behavior I'm looking for although it's a little ugly.
$ readarray -t ARRAY < <(printf '%s\n' "first line" "second line")
$ for x in "${ARRAY[@]}"; do echo $x; done
first line
second line
Does anyone know of a better way to do this? Am I missing something?
readarrayis the proper way to do this. There is nothing ugly about it. The only ugly thing is you are using all capital letters for your variable name where you should be using all lowercase.