Redirecting Output

Suppose you've developed your resume and spell-checked it. As you learned in the previous section, the results you see onscreen will be the output of the last commandin this case, a list of misspelled words. A lot of times, you'll want to redirect the final output to another location, such as to a file or a printer (if a printer is an option for you), rather than view it onscreen. You can do this using redirection, which sends the final output to somewhere other than your screen.

As shown in Code Listing 1.6, you will often redirect output results to a file. Notice the greater-than symbol (>), which indicates that the output of the program is to be redirected to the location (or filename) you specify after the symbol.

In the following examples, we'll show you how to redirect output to a new file and how to redirect output to append it to an existing file.

Code Listing 1.6. In this case, the output of ls gets redirected to local.programs.txt, as indicated by the greaterthan (>) symbol. The asterisk wildcard (*) acts as a placeholder for letters or numbers. Finally, the listing of /usr/bin gets appended to the other.programs.txt file.

[jdoe@frazz jdoe]$ ls /usr/local/bin > local.programs.txt [jdoe@frazz jdoe]$ ls local* localize localono local.programs.txt localyokel [jdoe@frazz jdoe]$ ls /usr/bin >> other.programs.txt [jdoe@frazz jdoe]$ 

To Redirect Output to a New File:


ls /usr/local/bin > local.programs.txt

In this case, we start with the ls command and a specific directory, add a greater than symbol (>), and then specify a filename. This will redirect the output of ls to a file named local.programs.txt.

Be careful with this! If the file already exists, it could be replaced with the output of the ls program here.


ls local*

Here, we're just checking to see that the new local.programs.txt file has successfully been created. The asterisk wildcard (*) specifies that we want a list of all files that begin with the word local, such as localize, localyokel, or localuno (see Code Listing 1.6). See the next section, Using Wildcards, for handy wildcard information.

To Append Output to an Existing File:

  • ls /usr/bin >> all.programs.txt

    Appending output to an existing file is similar to redirecting it to a new file; however, instead of creating a new file to hold the output (or replacing the contents of an existing file), you add content to the end of an existing file. Notice that you use two greater-than symbols here, rather than one.


  • You can pipe and redirect at the same time. For example, you might list a directory, pipe it to wc to count the entries, then append the results to a directoryinfo file, like this: ls | wc l >> directoryinfo. You can learn more about counting files and their contents with wc in Chapter 6.

Unix(c) Visual Quickstart Guide
UNIX, Third Edition
ISBN: 0321442458
EAN: 2147483647
Year: 2006
Pages: 251

Similar book on Amazon © 2008-2017.
If you may any questions please contact us: