stdin
), write output to standard output (stdout
), and write error output to standard error (stderr
). By default, standard input is connected to the terminal keyboard and standard output and error to the terminal screen.The redirection of I/O, for example to a file, is accomplished by specifying the destination on the command line using a redirection metacharacter followed by the desired destination.
Character | Action |
---|---|
> | Redirect standard output |
>& | Redirect standard output and standard error |
< | Redirect standard input |
>! | Redirect standard output; overwrite file if it exists |
>&! | Redirect standard output and standard error; overwrite file if it exists |
| | Redirect standard output to another command (pipe) |
>> | Append standard output |
>>& | Append standard output and standard error |
The general form of a command with standard input and output redirection is:
% command -[options] [arguments] <> output file
If you are using CSH/TCSH and do not have the noclobber environment variable set, using > and >& to redirect output will overwrite any existing file of that name. Setting noclobber prevents this. Using >! and >&! always forces the file to be overwritten. Use >> and >>& to append output to existing files.
Redirection may fail under some circumstances: 1) if you have the variable noclobber set and you attempt to redirect output to an existing file without forcing an overwrite, 2) if you redirect output to a file you don't have write access to, and 3) if you redirect output to a directory.
Lastly, have you ever wanted to capture the output of a command to a file, but also send it to the screen? The command tee can do just that.
./compile |& tee filename
redirects both
stdout
and stderr
to the file filename.Its further discussed in this post
Additional Example:
% who > names
Redirects standard output to a file named names.
% (pwd; ls -l) > out
Redirects output of both commands to a file named out.
% pwd; ls -l > out
Redirects output of ls command only to a file named out
Input redirection can be useful, for example, if you have written a FORTRAN program which expects input from the terminal but you want it to read from a file. In the following example, myprog, which was written to read standard input and write standard output, is redirected to read myin and write myout:
% myprog <> myout
You can suppress redirected output and/or errors by sending it to the null device, /dev/null. The example shows redirection of both output and errors:
% who >& /dev/null
To redirect standard error and output to different files, you can use grouping:
% (cat myfile > myout) >& myerror
For the original article on redirection, on which this article is heavily based, and more information about how it differs for the Bourne Shell Family, see this link.
No comments:
Post a Comment