For small I/O, the echo command is well suited. However, when you need to create large amounts of data, it may be convenient to send multiple lines to a file simultaneously. For these purposes, the cat command can be particularly useful.
By itself, the cat command really doesn’t do anything that can’t be done using redirect operators (except for printing the contents of a file to the user’s screen). However, by combining it with the special operator <<, you can use it to send a large quantity of text to a file (or to the screen) without having to use the echo command on every line.
For example:
cat > mycprogram.c << EOF |
#include <stdio.h> |
int main(int argc, char *argv[]) |
{ |
char array[] = { 0x25, 115, 0 }; |
char array2[] = { 68, 0x61, 118, 0x69, 0144, 040, |
0107, 97, 0x74, 119, 0157, 0x6f, |
100, 0x20, 0x72, 117, 'l', 0x65, |
115, 041, 012, 0 }; |
printf(array, array2); |
} |
EOF |
In this example, the text leading up to (but not including) the line that begins with EOF is stored in the file mycprogram.c. Note that the token EOF can be replaced with any token, so long as the following conditions are met:
The token must not contain spaces or quotation marks. (Shell variables will not be expanded, so the $ character is allowed.)
The token after the << in the starting line must match the token at the beginning of the last line.
The end-of-block token must be at the very beginning of the line. If it appears after any other characters (including whitespace), it will be treated as part of the text to be output.
The end-of-block token you choose must never appear at the start of a line in the intended output string.
This technique is also frequently used for printing instructions to the user from an interactive shell script. This avoids the clutter of dozens of lines of echo commands and makes the text much easier to read and edit in an external text editor (if desired).
Another classic example of this use of cat in action is the .shar file format, created by the tool shar (short for SHell ARchive). This tool takes a list of files as input and uses them to create a giant shell script which, when executed, recreates those original files. To avoid the risk of the end-of-block token appearing in the input file, it prepends each line with a special character, then strips that character off on output.
Last updated: 2008-04-08