echo "The old method" > temp.txtSide 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.
echo "Appending a second line to the file >> temp.txt
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 << EOFThe 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 Old Method
Appending a second line to the file
EOF
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 <<EOFUsing the technique of appending mentioned above, along with the HERE document, we can also grow our HERE document. E.g.
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 <<EOFThe results of the above script would be (inside tmp1 file):
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
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