What does a -d ''
do in a bash read command? The example is directly from a previous SO. From the usage printed by the read command, it says that the -d
option defines the delimiter for splitting words in a line. What does an empty delimiter do?
read -d '' sql << EOF
select c1, c2 from foo
where c1='something'
EOF
echo "$sql"
I know by experimenting that with it the variable is assigned the multiple lines. Without it, only the first line is assigned. It seems hard to explain this behavior based on the usage text.
In bash read
builtin empty string delimiter -d ''
behaves same as using delimiter as a NUL byte or $'\0'
(as defined by ANSI C-quoted string) or in hex representation 0x0
.
-d ''
specifies that each input line should be delimited by a NUL byte. It means that input string is read up to the immediate next NUL character in each invocation of read
.
Usually it is used with IFS=
as:
IFS= read -r -d ''
for trimming leading and trailing whitespaces in input.
A common example of processing NUL delimited input is:
while IFS= read -r -d '' file; do
echo "$file"
done < <(find . -type f -print0)
find
command is printing files in current directory with NUL as the delimiter between each entry. read -d ''
sets \0
as delimiter for reading one entry at a time from output of find
command.Related: Why ‘read’ doesn’t accept \0 as a delimiter in this example?