Redirecting Input and Output

team bbl


Often commands need to receive input from the keyboard and/or send output to the screen. Whenever data is moved from one program or device to another, it is transferred in a stream. When a program runs, it is connected automatically to an input and an output stream: stdin and stdout. By default, stdin is connected to the keyboard and stdout is connected to the screen. You can redirect stdin and stdout.

The ls command outputs a list of files to stdout, which by default is connected to the screen. You can change the output location using the redirect metacharacterthe greater than sign (>), as follows:

 ls > dirlist 

The list of files is redirected to a file called dirlist and does not display on the screen. If dirlist doesn't exist, it's created. If dirlist exists, it's replaced. If you don't want to overwrite the file, you can append the output to the existing file, by using >>, instead of >. Or, you can set noclobber, a shell option that stops file overwriting, printing an informative message instead, such as "Can't overwrite existing file," as follows:

 set -o noclobber 

The redirect metacharacter for stdin is the lesser than sign (<). For example:

 mail < message 

The mail command inputs the text from the file named message, rather than from the keyboard, and sends the message via email.

A third stream called stderr is connected to running programs. Error messages use the stderr stream, which is connected by default to the screen. When you redirect output using >, stderr is not redirected; it still displays on the screen. To redirect stderr, use a command similar to:

 ls &> dirlist 

Now, both the list of files and any error message are sent to the file dirlist.

Sometimes you want to connect stdout on one program directly to stdin on another program. Making this type of connection is called piping and is done using the metacharacter|. Suppose you want to send a list of all the files in your directory directly to the printer. You can use the following command:

 ls | lpr 

    team bbl



    Spring Into Linux
    Spring Into Linux
    ISBN: 0131853546
    EAN: 2147483647
    Year: 2005
    Pages: 362
    Authors: Janet Valade

    flylib.com © 2008-2017.
    If you may any questions please contact us: flylib@qtcs.net