I've been reading up on this post: bash "for in" looping on null delimited string variable to see if I would be able to handle arbitrary text containing spaces inside an array.
Based on the post above this works fine:
while IFS= read -r -d '' myvar; do echo $myvar; done < <(find . -type f -print0)
To check my understanding I also did this (which still works fine):
while IFS= read -r -d '' myvar; do echo $myvar; done < <(printf "%s\0" 'a b' 'c d')
However, then I attempt storing the output in an array it goes wrong:
IFS= read -r -d '' -a myvar < <(printf "%s\0" 'a b' 'c d')
The array holds only a b
and not c d
:
echo ${myvar[@]}
a b
Apparently, there is a finer detail I am missing here. Thanks for any help.
PS. I am running:
GNU bash, version 3.2.57(1)-release (x86_64-apple-darwin14)
Copyright (C) 2007 Free Software Foundation, Inc.
In bash
4.4, the readarray
command gained a -d
option analogous to the same option for read
.
$ IFS= readarray -d '' myvar < <(printf "%s\0" 'a b' 'c d')
$ printf "%s\n" "${myvar[@]}"
a b
c d
If you must support earlier versions, you need to loop over the output explicitly.
while IFS= read -d '' line; do
myvar+=( "$line" )
done < <(printf "%s\0" 'a b' 'c d')
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With