Manipulating Input and Output Redirection

Text-mode Linux programs operate on three input/output streams, each of which is treated much like a file: Standard input (stdin) is normally tied to the keyboard and is the method programs use to accept input from the user. Standard output (stdout) is normally tied to the screen, xterm window, or other text-mode display tool, and it displays normal program output. Standard error (stderr) is also usually tied to the text-mode display, but it handles high-priority messages such as error reports. Linux can readily redirect these input and output streams. Therefore, you can capture the output of a text-mode program in a file or send the contents of a file to a program as input. You do this by using redirection operators, as detailed in Table 4.2.

Table 4.2: Common Redirection Operators

Operator

Action

<

Redirects stdin to use the specified file.

>

Redirects stdout to the specified file, overwriting the existing file's contents.

»

Redirects stdout to the specified file, appending to the existing file's contents.

2>

Redirects stderr to the specified file, overwriting the existing file's contents.

Redirects stderr to the specified file, appending to the existing file's contents.

&>

Redirects both stdout and stderr to the specified file, overwriting the existing file's contents.

Each operator takes a filename as a parameter. You can combine multiple operations. For instance, to pass the contents of data.txt to numcrunch and to save the program's output in out.txt, you could type:

Tip Redirection is often used as a way to quickly obtain "junk" data or throw away data. Specifically, if you want a lot of empty input, you can use input redirection to obtain data from /dev/zero, which generates a limitless supply of binary 0 values. To get rid of a program's output, redirect it to /dev/null; the output vanishes forever.

0 0

Post a comment