Redirecting command output to a file
Commands entered at the command line typically use the three standard files described previously, but you can redirect the output for a command to a file you name. If you redirect output to a file that does not already exist, the system creates the file automatically.
Most shell commands display information about your workstation
screen, standard output. If you redirect
the output, you can save the output from a command in a file instead.
The output is sent to the file rather than to the screen. At the end
of any command, enter:
>filename
For
example:
cat file1 file2 file3 >outfile
writes the contents
of the three files into another file called outfile.
All the information in the original three files is concatenated into
a single file, outfile.When you redirect output with >filename and it
is an existing file, the output writes over any information that the
file already contains. To append command output
at the end of the file, use:
>>filename
instead. Another example:
(sort -u file1 >output) >&outerr
redirects the result of the sort to the file named output (instead of standard output) and redirects
any error messages to the file outerr, which
is a record of errors encountered during various sorts.Suppose you entered:
sort -u filea >output
In
this command, you see two redirections:
- Error output from the sort is redirected to standard output, the display screen.
- The result of the sort is redirected to the file named output.
Here is another example of redirection, sending both standard error
and standard output to a file. This command produces the program hello and a listing with error messages in a file
called hello.list:
c89 -o hello -V hello.c >&hello.list