Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

bash “read -a” looping on null delimited string variable

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.
like image 210
Tore H-W Avatar asked Jan 01 '16 10:01

Tore H-W


Video Answer


1 Answers

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')
like image 193
chepner Avatar answered Sep 20 '22 01:09

chepner