Wednesday, July 14, 2010

LINUX: The Power of HERE Documents

After doing things the manual, brute force way, you will be able to truly appreciate the elegance of HERE documents. If you wanted to create a file with a few lines of text in them, you would redirect the echo command to it. E.g.
echo "The old method" > temp.txt
echo "Appending a second line to the file >> temp.txt
Side note--a single redirect arrow, the "greater than" sign, will create a new file called temp.txt containing the text on the left hand side. The double redirect arrow as shown on the second line, will not create a new file (nor erase the contents of the existing one), but rather, it will append to it.

So that method is okay for doing a few small things, but it isn't efficient or powerful when your needs are greater. We can use a HERE document to put several lines of text into a file without having to continuously echo and redirect. A HERE document can be used for more that just this, but that is the focus of this post. So, the example is as follows:
cat > temp.txt << EOF
The Old Method
Appending a second line to the file
EOF
The temp.txt and EOF can be changed to whatever you want. The temp.txt is just a file to dump the text into. The EOF is a label to indicate the beginning and end of the HERE document. Notice that there is a matching EOF at the end. If you wanted to use the word HERE, that is perfectly fine, just make sure that at the end of the section to put into the file, you write a matching HERE to indicate the end of the block.

The end result of the two methods are the same, however the HERE document scales much better. You can put a 100 lines of text right in there if you desired with little effort.

There is even more power to be had here. We can do things like executing commands at run time when compiling the HERE document. E.g.
cat > tmp1 <<EOF
this is the first file
this is the 2nd line of 1st file
`echo hello`
did the above come out as "hello" or echo hello?
no, it executed the echo and just printed hello...nice
EOF
Using the technique of appending mentioned above, along with the HERE document, we can also grow our HERE document. E.g.
cat > tmp1 <<EOF
this is the first file
this is the 2nd line of 1st file
`echo hello`
did the above come out as "hello" or echo hello?
no, it executed the echo and just printed hello...nice
EOF

cat >> tmp1 <<EOF
did everything get deleted?
nope, it appended
EOF
The results of the above script would be (inside tmp1 file):
this is the first file
this is the 2nd line of 1st file
hello
did the above come out as "hello" or echo hello?
no, it executed the echo and just printed hello...nice
did everything get deleted?
nope, it appended


No comments:

Post a Comment