This excerpt is from the new 3rd Ed. of ‘A Practical Guide to Linux: Commands, Editors, and Shell Programming’, authored by Mark Sobell, published by Pearson/Prentice Hall Professional, Sept. 2012, ISBN 013308504X. For more info, please visit http://www.sobell.com/
The term redirection encompasses the various ways you can cause the shell to alter where standard input of a command comes from and where standard output goes to. By default,
the shell associates standard input and standard output of a command with the keyboard and the screen. You can cause the shell to redirect standard input or standard output of any command by associating the input or output with a command or file other than the device file representing the keyboard or the screen. This section demonstrates how to redirect input/output from/to text files and utilities.
Redirecting Standard Output
The redirect output symbol (>) instructs the shell to redirect the output of a command to the specified file instead of to the screen (Figure 5-6). The syntax of a command line that redirects output is
command [arguments] > filename
where command is any executable program (e.g., an application program or a utility), arguments are optional arguments, and filename is the name of the ordinary file the shell redirects the output to.
Figure 5-7 uses cat to demonstrate output redirection. This figure contrasts with Figure 5-5, where standard input and standard output are associated with the keyboard and screen. The input in Figure 5-7 comes from the keyboard. The redirect output symbol on the command line causes the shell to associate cat’s standard output with the sample.txt file specified following this symbol.
Redirecting output can destroy a file I
Use caution when you redirect output to a file. If the file exists, the shell will overwrite it and destroy its contents. For more information see the tip “Redirecting output can destroy a file II” on page 139.
After giving the command and typing the text shown in Figure 5-7, the sample.txt file contains the text you entered. You can use cat with an argument of sample.txt to display this file. The next section shows another way to use cat to display the file.
Figure 5-7 shows that redirecting standard output from cat is a handy way to create a file without using an editor. The drawback is that once you enter a line and press RETURN, you cannot edit the text until after you finish creating the file. While you are entering a line, the erase and kill keys work to delete text on that line. This procedure is useful for creating short, simple files.