Unix & Linux Stack Exchange is a question and answer site for users of Linux, FreeBSD and other Un*x-like operating systems. Join them; it only takes a minute:

Sign up
Here's how it works:
  1. Anybody can ask a question
  2. Anybody can answer
  3. The best answers are voted up and rise to the top

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?

share|improve this question

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.

share|improve this answer
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.... – fedorqui 10 hours ago
    
@fedorqui thanks, hope it's clearer now. – heemayl 7 hours ago

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_
share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.