Reputation: 1
Forgive me if this is obvious but I can't reason it out. The intent was to assign a heredoc to a variable in bash. The correct code on this site is:
read -r -d '' VAR <<'EOF'
abc'asdf"
$(dont-execute-this)
foo"bar"''
EOF
This works very well. But I don't see why read wouldn't load the data into VAR
without a redirect.
-d sets the delimiter as single quote. Shouldn't bash absorb all the following data until it encounters a '
and put the lot into VAR
?
This doesn't happen, of course. I'm just wondernig why not.
Upvotes: 0
Views: 57
Reputation: 295315
read
reads from stdin -- not from your script's source file. It would be pretty useless (for prompting the user, reading from a separate file, etc) otherwise. See BashFAQ #1 for more on its use.
If you run a script at a terminal, then, read
by default reads from that terminal; if you pipe content into your script, read
by default reads from that content; etc.
read -r -d '' var
, specifically, reads from stdin until a NUL character is seen, or an end-of-file condition takes place (in the latter case, it exits with a nonzero status, but still populates the destination variable).
Using <<'EOF'
redirects your stdin from a temporary file containing the heredoc's contents. Thus, even though the file contains no NULs, it will eventually hit EOF, and thus control will return.
Upvotes: 3