echo with a here-document

I do not know how valid this post is, but here it is.

I was writing a script for testing some development code that I had written. It involved many echo statements to redirect the output into a log file.

Given the large number of echo statements, I took to this solution

cat <<EOF >> /tmp/log
A Line in the log file.
The next line in the log file.
And the last line in the log file.
EOF

which will produce

$ cat /tmp/log
A Line in the log file.
The next line in the log file.
And the last line in the log file.

Since there were many occurences of these cat command (and also being a case of UUOC), I thought of using the here-document in the following manner to arrive at the same solution as above.

echo <<EOF >> /tmp/log
A Line in the log file.
The next line in the log file.
And the last line in the log file.
EOF

But in this case, /tmp/log was empty.

Look at the man pages of sh and ksh, it says

ksh
       << marker
              after  reading the command line containing this kind of redirec-
              tion (called a here document), the shell copies lines  from  the
              command  source  into  a  temporary  file  until a line matching
              marker is read.  When the command is executed, standard input is
              redirected  from  the  temporary  file. 
sh
   Here Documents
       This  type  of  redirection  instructs the shell to read input from the
       current source until a line containing  only  word  (with  no  trailing
       blanks)  is seen.  All of the lines read up to that point are then used
       as the standard input for a command.

Basically, the here document would be written into some temporary file and then re-read. If that be the case, why doesnt the echo with here documents work ?

I went through the The Open Group Base Specifications Issue 6 - UNIX Specification for echo and here-document. They dont say anything in particular about this.

Opinions/suggestions/remarks are welcome.

Thanks,
vino

Hey vino,

I also have in my installation script many lines that should be inserted into a file.
I did it in the following way:

echo "A Line in the log file.
The next line in the log file.
And the last line in the log file." > /tmp/log

Nir

I assume its because echo (unlike most unix commands) does not 'by default' read from the stdin descriptor. All these commands simply echo a new line:

a) echo "mystring" | echo
b) cat myfile | ehho
c) echo < myfile
d) echo <<EOF
blah1
blah2
EOF

So in your second example:

you are in effect doing:

echo < myinfile > myoutfile

it's just the shell is creating the file for you.