6

I have a problem, while creating a script from a master one:

As simple as:

cat  pippo << EOF
LOGFILE=test.log    
echo '#############################' >> $LOGFILE
EOF

. But, when I inspect pippo I get:

LOGFILE=test.log
echo '#############################' >>
EOF

Why the $LOGFILE has been replaced?

2 Answers 2

11

Here document by default subjects to shell expansions, precisely parameter expansion, command substitution, and arithmetic expansion. So variable (parameter) expansion is happening in your case -- the variable LOGFILE is being expanded in the current shell, and as the variable presumably does not exist hence null is being returned (and replaced) as the expanded value.

To get the shell metacharacters literally in a here doc, use quotes around the terminator string:

cat pippo <<'EOF'  ## "EOF" would do too
LOGFILE=test.log    
echo '#############################' >>"$LOGFILE"
EOF

Also quote the variable expansion as (presumably) it refers to a filename, so that word splitting and pathname expansion are not done on it after expansion.

1
  • 2
    From Bash ref → 3.6.6 Here Documents If word is unquoted, all lines of the here-document are subjected to parameter expansion, command substitution, and arithmetic expansion.... Commented Dec 12, 2016 at 14:46
0

To actually have a pippo file, you need to do:

cat > pippo <<EOF

Which redirects the values in the here-document to the file named pippo.

Then, to have the contents inside the here-doc piped exactly as written and not expanded, evaluated or changed, you need to quote the word after the <<.
Any of this (even partial quotes work):

<<'EOF'
<<"EOF"
<<\EOF
<<E"O"F
<<E\OF

If there is no quoting, the value of variable "$LOGFILE" gets expanded to its value, which seem to be null in your environment, and gets lost.

In short, use something like this:

cat > pippo << \_EOF_
LOGFILE=test.log    
echo '#############################' >> $LOGFILE
_EOF_

You must log in to answer this question.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.