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

旧时模样 提交于 2019-12-22 11:25:10

问题


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.

回答1:


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')


来源:https://stackoverflow.com/questions/34555278/bash-read-a-looping-on-null-delimited-string-variable

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!