October 03, 2001, 2:09 PM — Redirection allows a user to redirect output that would normally go to the screen and instead send it to a file or another process. Input that normally comes from the keyboard can be redirected to come from a file or another process.
When a typical Unix utility starts up, three files are automatically opened for you inside of it. These files are given file descriptor numbers inside the program -- 0, 1, and 2 -- but they're more commonly known as stdin (standard in -- file descriptor: 0), stdout (standard out -- file descriptor: 1) and stderr (standard error -- file descriptor: 2). When the program starts, default assignments for these files are made to
/dev/tty, which is the device name for your terminal. The stdin file is assigned to the keyboard of your terminal, while stdout and stderr are assigned to its screen.
Let's start with a simple example using
grep. Type a
grep command to find lines containing the word hello, then type the following lines at your terminal. At the end of each line press Enter to move down to the next line. Watch what happens as you type
$ grep "hello" Now is the time for every good person to say hello.
The screen repeats the last line.
$ grep "hello" Now is the time for every good person to say hello. say hello.
Hold down the Control key and press D to end the input to
grep. Control-D is an end-of-file marker and can be entered as a keystroke to stop any utility that is taking its input from the keyboard.
grep "hello" line is a command to search standard input for lines containing hello and echo any such line found to standard output. The Unix console automatically echoes anything you type, so the three lines appear on the screen as you type them. Then
grep hits a line containing hello and decides to output it to standard out, and
say hello appears on the screen a second time. The second appearance is the output from