Apple Developer Connection
Member Login Log In | Not a Member? Contact ADC

< Previous PageNext Page > Hide TOC

Bulk I/O Using the cat Command

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:

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.

C Shell Note: The multi-line cat syntax is the same in the C shell and the Bourne shell.



< Previous PageNext Page > Hide TOC


Last updated: 2008-04-08




Did this document help you?
Yes: Tell us what works for you.

It’s good, but: Report typos, inaccuracies, and so forth.

It wasn’t helpful: Tell us what would have helped.
Get information on Apple products.
Visit the Apple Store online or at retail locations.
1-800-MY-APPLE

Copyright © 2007 Apple Inc.
All rights reserved. | Terms of use | Privacy Notice