The purpose of this lesson is to show how you can redirect the output or input of a Unix command.
When you issue a Unix command like date, the output of the command goes to what is called standard output.
When you are using a Unix window on a PC or if you are using a Unix terminal, the standard output is the screen, so you can see the results of your command.$ date Tue Dec 19 21:16:03 CST 2000 $
In Unix, you can redirect standard output to go to a file. This output redirection is very useful if you want to save the output of a command to a file rather than just letting it flash across the screen and eventually scroll away from view.
You can redirect standard output to go to a file by using the > sign after the command and before a file name. For example, you can redirect the output of the date command to a file called apple:
Notice that we did not see the date appear on the screen. The date is in the file apple. We can use the cat command to show what is in apple.$ date > apple $
$ cat apple Tue Dec 19 21:16:43 CST 2000 $
When you use the > for redirecting standard to the file, Unix puts what would appear in standard output into the file. This erases what would previously have been in the file.
$ cat apple Tue Dec 19 21:16:43 CST 2000 $ date > apple $ cat apple Tue Dec 19 21:17:07 CST 2000 $
Notice the output of the date command stored in apple has changed.
If you want to keep adding content to a file using redirection, use the >> symbol (two > right in a row, no spaces). The >> symbol appends what would go to standard output to a file. So, for example, we can do this:
$ cat apple Tue Dec 19 21:17:07 CST 2000 $ date >> apple $ cat apple Tue Dec 19 21:17:07 CST 2000 Tue Dec 19 21:17:53 CST 2000 $
Notice that apple in the end now has two lines of output from the date command in it.
Just as Unix calls the default place where it places output from a command the standard output, Unix has a name for where it gets, by default, the input for commands. Unix calls this the standard input. In a Unix window or on a Unix terminal, the standard input is the keyboard.
We can use the < sign to redirect the standard input to be from a file rather than a keyboard.
So while the mail command normally requires input from a keyboard, we can do this one-line mail trick to use input from a file.
Experiment with redirecting the standard output of many Unix commands (such as ls, who, uname) to a file and use the cat command to look at what you put into the files. Try experimenting with both the > and >> operators.
Then try doing some redirection of input on the same line. You can try it with the cat command, or try this one line mail trick.