Chapter 43. Redirecting Input and Output

Using Standard Input and Output

There is basically no difference between reading data from a file and reading data from a terminal.[1] Likewise, if a program’s output consists entirely of alphanumeric characters and punctuation, there is no difference between writing to a file, writing to a terminal, and writing to the input of another program (as in a pipe).

The standard I/O facility provides some simple defaults for managing input/output. There are three default I/O streams: standard input, standard output, and standard error. By convention, standard output (abbreviated stdout) consists of all “normal” output from your program, while standard error (stderr) consists of error messages. It is often a convenience to be able to handle error messages and standard output separately. If you don’t do anything special, programs will read standard input from your keyboard, and they will send standard output and standard error to your terminal’s display.

Standard input (stdin) normally comes from your keyboard. Many programs ignore stdin; you name files directly on their command line — for instance, the command cat file1 file2 never reads its standard input; it reads the files directly. But without filenames on the command line, Unix commands that need input will usually read stdin. Standard input normally comes from your keyboard, but the shell can redirect stdin from a file. This is handy for Unix commands that can’t open files directly — for instance, ...

Get Unix Power Tools, 3rd Edition now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.