You may have seen scripts containing something like this:

cat << EOF
What you are about to do is a really really really bad thing.
Only do this if you are absolutely sure you want to do it.

Are you absolutely sure that you want to do this? [[y/N]

(Well, you won't have seen anything like that, because the UnixWay is to shoot first and never ask questions!)

This is what is called a Here Document. The << operator instructs the shell to read your typed input and use all those lines as interactive input to the command that occurred before the <<.

Here documents are handy for issuing multi-line commands to interactive programs such as sed, ftp, cat etc.

The format is:

 <<[[-] word
     Line 1
     Line 2
     Line 3

Almost always it is the case that delimiter=word but it is possible that word and delimeter may differ (especially if any of the characters in word are quoted), but that's incredibly rare. If you need to know the intracacies, see the bash page. If you put a - after the << then all leading tab characters are stripped from the input lines; this means you can lay out commands as you would normally and they will all be entered without the tabs.

A variant on the here document is the Here String which uses three <'s to expand a word and supply it to the command on stdin.

 foo <<< word

Why would you use such a thing? For documentation, compare:

cat << EOF
foo bar
foo bar
bar foo
bar baz foo
foo bar foo

echo foo bar
echo foo bar
echo bar foo
echo bar baz foo
echo foo bar foo

Then compare that in a twenty line block. Makes writing the documentation easier and checking it painless (did you mean to mention 'echo' at the beginning of a line and your mind skipped over it because all the lines began with echo?)

Another very important use is automating commands such as FTP that don't otherwise provide a method for scripting;

 ftp -n <<EOF
 user anonymous ${USER}@
 cd /path/to/file
 get file.gz2

See bash(1).

So Remember, if you ever need to automate an interactive bash program keep Here Documents in mind. BUT Don't forget that sometimes it's easier to have an already made file containing all the commands!


  • ftp -n < ftp_instructions