Information on heredoc

Hi ,

I am using ksh on Aix 7.1 and found the below code in a script which is a bit confusing to me, any help will be appreciated

<<comments
put ${pathforfiles}/${ftpfilename}
put ${logs}/${filename}.sch
put ${logs}/${filename}.tgr
comments

I have searched for information on heredoc but did not find any article that says what would happen if there is no command to which heredoc is passed

Thanks

Shell Command Language
This indicates that it writes to stdin by default.
Nested here documents example:

#!/bin/bash
$cat <<eofa; cat <<eofb
$>>test1
$>>test2
test1 
test2

$<<eofa; cat <<eofb
$>>test1
$>>test2

test2

In the second block the first instance does not have stdin defined as an output device, and so nothing is there to output or process the data "test1".

I think Don Cragun probably knows more.

This is cute...

There is a comment in the POSIX Standard's rationale for the simple commands section of the shell command language description that says:

But, I don't see anything in the standard that clearly specifies for what a here-document without a command is providing input. With the command exec a here-document does replace standard input for the current shell execution environment.

Playing around a little bit with the above example code in the POSIX rationale and the code supplied in post #1 in this thread, it appears to me that the here-document:

<<comments
put ${pathforfiles}/${ftpfilename}
put ${logs}/${filename}.sch
put ${logs}/${filename}.tgr
comments

is a shell language comment similar to the C language comment:

/*
put ${pathforfiles}/${ftpfilename}
put ${logs}/${filename}.sch
put ${logs}/${filename}.tgr
*/

except that any expansions occurring in that here-document may have side effects. For example:

count=0
IFS=:
while read a b
do	echo $a
	<<comment
	This comment counts lines read from the input file
	$((++count))
	comment
done </etc/passwd
echo "$count lines were read from /etc/passwd"

might produce abbreviated output similar to:

root
nobody
daemon
...
108 lines were read from /etc/passwd

If you wanted a multi-line shell comment without side effects (like the C example I showed earlier) you could quote one or more characters in the EOF string of the here-document:

count=0
IFS=:
while read a b
do	echo $a
	<<"comment"
	This comment counts lines read from the input file
	$((++count))
	comment
done </etc/passwd
echo "$count lines were read from /etc/passwd"

which would then produce abbreviated output similar to the following (with the last line being exactly like that shown below):

root
nobody
daemon
...
0 lines were read from /etc/passwd

Are we having fun yet? :cool:

3 Likes