Input, Output, and Redirection
Another set of very useful tools are the input/ output and redirection tools.
When you log into your UNIX account, the Operating System creates three "streams of data" for you to play with: standard input, standard output and standard error. Standard input is typically a keyboard that allows you to send characters to the computer. Standard output, on the other hand is usually a monitor that is used by the computer to display characters to the user. Finally, standard error is used by the computer to notify the user of errors. In your case, standard error will often be the monitor as well.
UNIX allows you to manipulate these streams in many useful ways. Specifically, you can change where these streams of data lead. For example, you might send the output of a command to a file instead of to the monitor. Likewise, you might send a saved set of commands in a file to the standard input of a command. To perform input and output redirection you use the "<" and ">" characters respectively
Let's look at a few examples.
To send the standard output of a command to a file instead of a monitor you would put the command on the left and the filename to the right of the ">" character like:
This would create a file called directory_listing.txt that would contain a list of all the files in the current directory.
What happens if there was already a file called directory_listing.txt? Well, it would be erased. If you want to append to an existing file instead of overwriting it, you must use the ">>" syntax such as
|Standard error works much the same way but
uses the "2>" syntax instead of the ">" syntax such as in the
following example which sends error messages from the ls
command to the file error.txt (there is no -U option).
ls -U 2> error.txt
Standard input works using the "<" character. Thus, to send a set of pre-saved parameters to a command you might do something like the following
Finally, you should note that you can string input and output so that the following example would save the contents of unsorted.txt in a sorted order in the file sorted.txt
Pipes (pipelines) work much like redirection except that the work strictly on sets of commands. Specifically pipes allow you to send the standard output of one command to another command such as in the following case which sends the direfctory listing to the sort comand which sorts the directory in dictionary order:
Note that a pipeline can be as long as is reasonable. Thus, you might see a pipeline such as:
cat directory_listing | grep .html | sort | more
Of course, we will discuss all of these utilities later, but you get the picture. Just think that when you see "X | Y | Z" you should say to yourself "Execute X and send the output to Y. Then send the output of Y to Z."