Sending multiple lines of input to a program

Contributor Icon Contributed by Rex Date Icon October 20, 2003  
Tag Icon Tagged: UNIX shell scripting

Using a ‘here document’ it is possible to send multiple lines of input to a program from a shell script.


A here document uses the << I/O redirector followed by a code. The subsequent lines are redirected to the program until the specified code. The basic syntax is:

program << CoDe
Line of input
More input

extra input
CoDe

The code needs to be something that would not occur in the text. This technique is useful for working with interactive programs like ftp. In the following example, a file specified in a shell variable ($filename) is retrieved from an ftp server:

filname=important.file.gz
ftp -n ftp.server.name << TheEnd
user username password
cd directory/subdir
get $filename
quit
TheEnd

Previous recipe | Next recipe |
 
  • Anonymous
    It's possible even to create a multi-line file, using this method:

    cat<<EOF > /tmp/MY_NEW_FILE
    line 1
    one more line
    ...
    last line
    EOF
  • qmchenry
    I can never remember the term for this technique, but Rex, one of the many who have contributed recipes to Tech-Recipes has a recipe describing this and I look to it to remember that they are called here documents. I think it is one of the more obscure but useful tips in shell scripting.

    Anyone who knows about here docs definitely has a strong background in UNIX. If you are willing to share any more tips, you can add them as an official recipe in the category hierarchy that you feel is appropriate. If they are new recipes, we'll validate them and you'll be compensated... A hint to any recipe authors and future Tech Chefs out there, it's a good idea to do a little search first to see if your idea for a recipe is in our cookbook of over a thousand recipes.

    Quinn
blog comments powered by Disqus