I thought it was impossible to use '\0' as a delimiter in bash, but noticed yesterday that Gentoo’s
ebuild.sh had pipelines like this:
find ..... -print0 |
while read -r -d $'\0' x; do
# Do something with file $x
done
This makes it possible to handle any strange filenames correctly, even if the filename contains newline (
'\n') or carriage return (
'\r') characters. (Some other commands, including
sort and
xargs, have options to make null character the delimiter based on the same reason.)
Because BASH internally uses C-style strings, in which
'\0' is the terminator,
read -d $'\0' is essentially equivalent to
read -d ''. This is why I believed
read did not accept null-delimited strings. However, it turns out that BASH actually handles this correctly.
I checked BASH’s souce code and found the delimiter was simply determined by
delim = *list_optarg; (
bash-3.2/builtins/read.def, line 296) where
list_optarg points to the argument following
-d. Therefore, it makes no difference to the value of
delim whether
$'\0' or
'' is used.