Content deleted Content added
Thanh061093 (talk | contribs) Created by translating the page "Redirection (computing)" |
Thanh061093 (talk | contribs) No edit summary |
||
Line 1:
{{distinguish|URL redirection}}
{{no footnotes|date=January 2017}}
[[Image:Stdstreams-notitle.svg|thumb|300px|The standard streams for input, output, and error]]
In [[computing]], '''redirection''' is a form of [[interprocess communication]], and is a function common to most [[command-line interpreter]]s, including the various [[Unix shell]]s that can redirect [[standard streams]] to user-specified locations.
==Redirecting standard input and standard output==
Redirection is usually implemented by placing certain [[token (parser)|characters]] between [[command (computing)|commands]].
===
<syntaxhighlight lang="bash" inline
===
<syntaxhighlight lang="bash">
tr a-z A-Z << END_TEXT
one two three
uno dos tres
END_TEXT
</syntaxhighlight>
To read from a string, one can use a [[here string]], using the <code><<<</code> operator: <syntaxhighlight lang="bash" inline>tr a-z A-Z <<< "one two three"</syntaxhighlight>, or:
<syntaxhighlight lang="bash">
NUMBERS="one two three"
tr a-z A-Z <<< "$NUMBERS"
</syntaxhighlight>
==Piping==
[[
The two programs performing the commands may run in parallel with the only storage space being working buffers (Linux allows up to 64K for each buffer) plus whatever work space each command's processing requires. For example, a "sort" command is unable to produce any output until all input records have been read, as the very last record received just might turn out to be first in sorted order. Dr. Alexia Massalin's experimental operating system, [[Synthesis kernel#Massalin.27s Synthesis kernel|Synthesis]], would adjust the priority of each task as they ran according to the fullness of their input and output buffers.
This produces the same end result as using two redirects and a temporary file, as in:
<syntaxhighlight lang="bash">
command1 > tempfile
command2 < tempfile
rm tempfile
</syntaxhighlight>
But here, <tt>command2</tt> does not start executing until <tt>command1</tt> has finished, and a sufficiently large scratch file is required to hold the intermediate results as well as whatever work space each task required. As an example, although DOS allows the "pipe" syntax, it employs this second approach. Thus, suppose some long-running program "Worker" produces various messages as it works, and that a second program, TimeStamp copies each record from ''stdin'' to ''stdout'', prefixed by the system's date and time when the record is received. A sequence such as <syntaxhighlight inline lang="bash">Worker | TimeStamp > LogFile.txt</syntaxhighlight> would produce timestamps only when Worker had finished, merely showing how swiftly its output file could be read and written.
<syntaxhighlight lang="bash">
cat infile | cmd
echo $string | cmd
echo -e 'user\npass' | ftp localhost
</syntaxhighlight>
can be replaced by:
<syntaxhighlight lang="bash">
cmd < infile
cmd <<< $string
ftp localhost <<< $'user\npass'
</syntaxhighlight>
As <code>echo</code> is often a shell-internal command, its use is not as criticized as cat, which is an external command.
==Redirecting to and from the standard file handles==
In [[Unix shell]]s derived from the original [[Bourne shell]], the first two actions can be further modified by placing a number (the [[file descriptor]]) immediately before the [[token (parser)|character]]; this will affect which stream is used for the redirection. The Unix standard I/O streams are:
{| class="wikitable"
! Handle !! Name !! Description
|-
| 0
| [[Standard streams#Standard input (stdin)|stdin]] || Standard input
|-
| 1
| [[Standard streams#Standard output (stdout)|stdout]] || Standard output
|-
| 2
| [[Standard streams#Standard error (stderr)|stderr]] || Standard error
|}
For example, <syntaxhighlight lang="bash" inline>command1 2> file1</syntaxhighlight> executes <tt>command1</tt>, directing the [[Standard streams#Standard error (stderr)|standard error]] stream to <tt>file1</tt>.
In shells derived from [[C shell|csh]] (the [[C shell]]), the syntax instead appends the <tt>&</tt> (ampersand) character to the redirect characters, thus achieving a similar result. The reason for this is to distinguish between a file named '1' and stdout, i.e. 'cat file 2>1' vs 'cat file 2>&1'. In the first case, stderr is redirected to a file named '1' and in the second, stderr is redirected to stdout.
Another useful capability is to redirect one standard file handle to another. The most popular variation is to merge [[Standard streams#Standard error (stderr)|standard error]] into [[Standard streams#Standard output (stdout)|standard output]] so error messages can be processed together with (or alternately to) the usual output. For example, <syntaxhighlight lang="bash" inline>find / -name .profile > results 2>&1</syntaxhighlight> will try to find all files named <tt>.profile</tt>. Executed without redirection, it will output hits to [[stdout]] and errors (e.g. for lack of privilege to traverse protected directories) to [[stderr]]. If standard output is directed to file <tt>results</tt>, error messages appear on the console. To see both hits and error messages in file <tt>results</tt>, merge [[stderr]] (handle 2) into [[stdout]] (handle 1) using '''<tt>2>&1</tt>'''.
If the merged output is to be piped into another program, the file merge sequence '''<tt>2>&1</tt>''' must precede the pipe symbol, thus, <syntaxhighlight lang="bash" inline>find / -name .profile 2>&1 | less</syntaxhighlight>
A simplified but non-POSIX conforming form of the command, <syntaxhighlight lang="bash" inline>command > file 2>&1</syntaxhighlight> is (not available in Bourne Shell prior to version 4, final release, or in the standard shell [[Debian Almquist shell]] used in Debian/Ubuntu): <syntaxhighlight lang="bash" inline>command &>file</syntaxhighlight> or <syntaxhighlight lang="bash" inline>command >&file</syntaxhighlight>.
It is possible to use <code>2>&1</code> before "<code>></code>" but the result is commonly misunderstood.
The rule is that any redirection sets the handle to the output stream independently.
So "<code>2>&1</code>" sets handle <code>2</code> to whatever handle <code>1</code> points to, which at that point usually is ''stdout''.
Then "<code>></code>" redirects handle <code>1</code> to something else, e.g. a file, but it does '''not''' change handle <code>2</code>, which still points to ''stdout''.
In the following example, standard output is written to ''file'', but errors are redirected from stderr to stdout, i.e. sent to the screen: <syntaxhighlight lang="bash" inline>command 2>&1 > file</syntaxhighlight>.
==Chained pipelines==
The redirection and piping tokens can be chained together to create complex commands. For example, <syntaxhighlight lang="bash" inline>sort infile | uniq -c | sort -n > outfile</syntaxhighlight> sorts the lines of <tt>infile</tt> in lexicographical order, writes unique lines prefixed by the number of occurrences, sorts the resultant output numerically, and places the final output in <tt>outfile</tt>. This type of construction is used very commonly in [[shell script]]s and [[batch file]]s.
==Redirect to multiple outputs==
The standard command <tt>[[tee (command)|tee]]</tt> can redirect output from a command to several destinations:<syntaxhighlight lang="bash" inline>ls -lrt | tee xyz</syntaxhighlight>. This directs the file list output to both standard output and the file <tt>xyz</tt>.
==See also==
*[[Here-document]], a way of specifying text for input in command line shells
*[[Shell shoveling]]
*[[Command substitution]]
*[[Process substitution]]
==External links==
*{{man|sh|dup|SUS|duplicate an open file descriptor}}
*[http://www.linfo.org/redirection.html Redirection Definition] by The Linux Information Project (LINFO)
*[http://tldp.org/LDP/abs/html/io-redirection.html I/O Redirection] in [http://tldp.org/ The Linux Documentation Project]
*[https://technet.microsoft.com/en-us/library/bb490982(en-us).aspx Redirection in Windows]
*[http://msdn.microsoft.com/en-us/library/ms682499(VS.85).aspx Creating a Child Process with Redirected Input and Output] in Windows
{{DEFAULTSORT:Redirection (Computing)}}
[[Category:Articles with example code]]
[[Category:DOS technology]]
[[Category:Unix software]]
[[Category:Unix]]
[[Category:Windows administration]]
[[pl:Standardowe strumienie]]
|