Brydon Gibson Brydon Gibson - 4 months ago 11
Bash Question

Where do I pipe to file when using an inline <<EOF ... EOF?

I am automating an ftp session, but I want to take stdout and pipe it to file. I have come up with 3 options:

Option 1

ftp -i ftpServer >stdoutFile <<EOF
cd somewhere
get something
EOF


Option 2

ftp -i ftpServer <<EOF >stdoutFile
cd somewhere
get something
EOF


Option 3

ftp -i ftpServer <<EOF
cd somewhere
get something
EOF > stdoutFile


I seem to be getting syntax errors with all of them, and none of them seem to work.

I feel like I've somehow got this to work before but I can't remember how.

Edit

The syntax errors are still present. It appears as though if I use this method with a here-document titled EOF, I can not use that delimeter anywhere else in the script - weird.

The exact error that is produced is actually a failure on the next if-statement termination. For example :

if [ condition ]
then
ftp -i ftpServer >stdoutFile <<EOF
cd somewhere
get something
EOF
fi

if [ something else ]
then
somethingWithaHereDoc <<EOF
foo
bar
EOF
fi


I get
Syntax error near unexpected token 'fi'
pointing to the line of the last fi.

The FTP connection is hanging now. I'm using a ~/.bashrc file and it works in another console, but not in the script. I accidentally had a named pipe in the directory, causing the ftp session to hang. All is resolved now. thanks!

The reason I am doing this is because I want to download a specific file from an ftp server. I am listing the directory content, exiting the ftp session and processing it in bash, and then starting another ftp session to get the file that I've chosen.

Answer

The <<EOF only signals that a here document will begin on the next line. You can freely mix this with other redirections, so options 1 and 2 are both valid. There is no difference between the two, although I suspect most people would prefer and suggest option 1, as it does not appear to "interject" the output redirection into the here document.

If you are getting syntax errors with either option 1 or option 2, they are almost certainly unrelated to the here document itself.

Option 3 is invalid because the here document delimiter must occur on a line by itself, and because it is not part of the original command.