Bash – How does the -d option to bash read work

bashoptionsquotingreadshell-script

I have a bash script where I'm trying to assign a heredoc string to a variable using read, and it only works if I use read with the -d ''
option, I.e.

read -d '' <variable>

script block

#!/usr/bin/env bash

function print_status() {
    echo
    echo "$1"
    echo 
}


read -d '' str <<- EOF
    Setup nginx site-config
    NOTE: if an /etc/nginx/sites-available config already exists for this
    website, this routine will replace existing config with template from
    this script. 
EOF

print_status "$str"

I found this answer on SO which is where I copied the command from, it works, but why?
I know the first invocation of read stops when it encounters the first newline character, so if I use some character that doesn't appear in the string the whole heredoc gets read in, e.g.

  • read -d '|' <variable> — this works
  • read -d'' <variable> — this doesn't

I'm sure it's simple but what's going on with this read -d '' command option?

Best Answer

I guess the question is why read -d '' works though read -d'' doesn't.

The problem doesn't have anything to do with read but is a quoting "problem". A "" / '' which is part of a string (word) simply is not recognized at all. Let the shell show you what is sees / executes:

start cmd:> set -x

start cmd:> echo read -d " " foo
+ echo read -d ' ' foo

start cmd:> echo read -d" " foo
+ echo read '-d ' foo

start cmd:> echo read -d "" foo
+ echo read -d '' foo

start cmd:> echo read -d"" foo
+ echo read -d foo