One of the powers of the Unix command line is the ability to redirect input and output of either end of the command (for most commands, anyway).
By default, Unix assumes that the default input will come from the keyboard, and the default output would go to the display. So, to view all the files in a directory, you type "ls" at the command line and the program returns to the display of all the files in a directory.
But you can also direct the output of a program to another source, such as to a text file. You can also specify a new source of input.
This is done using the ">" and the "<" characters.
For instance, say you want to get a list of files in a directory, but instead of having them appear on the screen, you want to put them in a new file, called ListOfInfo.txt. then you'd type:
$ls > ListOfInfo.txtAnd if you wanted to add more information to this file, you could append the info with ">>", i.e.:
$ps -aux>> ListOfInfo.txt(Otherwise, with just a single ">" Unix will just overwrite the contents of an existing file).
Just as ">" directs the output, using "<" will direct input. For instance...
$wc < ListOfInfo.txt...will give you the word count of the ListOfInfo.txt file.
You can mix and match these commands. For instance...
$wc < ListOfInfo.txt > WCResults.txtKeep in mind that not all Unix programs accept redirection, of either input or output. A command such as "mkdir" can't accept input or redirect its work elsewhere.
When running a shell, Unix keeps three different streams, or files, for input/output purposes. Each gets a file descriptor number (More on that later). They are:
Standard Input: The file that captures the input, usually from the keyboard (file descriptor # 0).
Standard Output: The file that captures the output, which is usually sen to the terminal display (It has a File descriptor # 1).
Standard Error: This file captures the error messages from the shell or the running program (It has a file descriptor # 2).
With this in mind, ">" really means "1>" and "<" is shorthand for "0<".
All this means you can redirect standard input output and error messages. For instance, say you want to capture an error message in a text file. You can't do that with the standard redirect. A wc on a nonexistent file reirected to an output file will not send the error message to the file. Instead, you can type:
$wc phonyfile.txt 2> ErrorFile.txtNote, you can also group these redirections for a single stream. "1>$2" sends standard output to the standard error file, and "2>$1" sends the error output to the standard output.
Note: This tutorial does not cover Unix pipes, which is a more powerful form of redirection. More on that later...