Redirection (computing): Difference between revisions

Content deleted Content added
Created by translating the page "Redirection (computing)"
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.
[[Tập tin:Stdstreams-notitle.svg|thumb|300x300px| Các luồng tiêu chuẩn cho đầu vào, đầu ra và lỗi ]]
Trong [[điện toán]], '''chuyển hướng''' là một hình thức giao tiếp giữa các tiến trình và là một chức năng phổ biến đối với hầu hết các trình thông dịch dòng lệnh, bao gồm các shell Unix khác nhau có thể chuyển hướng các luồng tiêu chuẩn đến các vị trí do người dùng chỉ định.
 
TrongIn [[Tương tự Unix|các-like]] hệoperating điều hành [[Tương tự Unix|giống Unix]]systems, cácprograms chươngdo trìnhredirection thựcwith hiện chuyển hướng vớithe <tt>[[Lời gọi hệ thống|lệnh gọi hệ thốngdup2]] <tt>dup2 (2)</tt> hoặc[[system kémcall]], linhor hoạtits hơnless-flexible nhưngbut mứchigher-level độ cao hơn tương tự[[Standard streams|stdio]] analogues, <tt>[[freopen ]](3)</tt> and <tt>[[popen ]](3)</tt> .
 
==Redirecting standard input and standard output==
== Chuyển hướng đầu vào tiêu chuẩn và đầu ra tiêu chuẩn ==
Redirection is usually implemented by placing certain [[token (parser)|characters]] between [[command (computing)|commands]].
Chuyển hướng thường được thực hiện bằng cách đặt các [[Phân tích từ vựng|ký tự]] nhất định giữa [[Mệnh lệnh (điện toán)|các lệnh]] .
 
=== Căn bản Basic===
Thông thườngTypically, the [[syntax]] phápof học|cúthese pháp]]characters is nhưas saufollows, sử dụngusing <code>&#x3Clt;</code> đểto chuyểnredirect hướng đầuinput, vào vàand <code>&#x3Egt;</code> để chuyển hướngto đầuredirect raoutput. <syntaxhighlight lang="bash" inline="">command1 > file1</syntaxhighlight> <span></span> thực thiexecutes <tt>command1</tt>, đặtplacing đầuthe raoutput trongin <tt>file1</tt>., Điềuas nàyopposed sẽto ghidisplaying đèit bấtat kỳthe dữterminal, liệuwhich hiệnis the trongusual destination for standard output. This will [[Clobbering|clobber]] any existing data in <tt>tệp1file1</tt> .
 
Sử dụngUsing <syntaxhighlight lang="bash" inline="">command1 < file1</syntaxhighlight> <span></span> thực thiexecutes <tt>command1</tt>, vớiwith <tt>file1</tt> as nguồnthe đầusource vào.of input, as opposed to the [[Computer keyboard|keyboard]], which is the usual source for standard input.
 
<syntaxhighlight lang="bash" inline="">command1 < infile > outfile</syntaxhighlight> <span></span> kết hợpcombines haithe khảtwo năngcapabilities: <codett>command1</codett> đọcreads từfrom <codett>infile</codett> and ghiwrites vàoto <tt>outfile</tt>
 
=== Biến thể Variants===
ĐểTo thêmappend vàooutput cuốito củathe tậpend tinof the file, chứrather khôngthan phảiclobbering it, ghithe đè nó,<code>&#x3Egt;&#x3Egt;</code> đượcoperator sửis dụngused: <syntaxhighlight lang="bash" inline="">command1 >> file1</syntaxhighlight> <span></span> .
 
ĐểTo đọcread từfrom mộta chuỗistream các dòngliteral (một tập tinan nhiềuinline dòngfile, truyềnpassed từngto dòngthe tớistandard các đầu vào tiêu chuẩninput), ngườione tacan use thể sử dụng mộta [[here document]], sửusing the dụng<code>&#x3Clt;&#x3Clt;</code> operator: <syntaxhighlight lang="bash" line="1">
<syntaxhighlight lang="bash">
tr a-z A-Z << END_TEXT
one two three
uno dos tres
END_TEXT
</syntaxhighlight>
</syntaxhighlight> Để đọc từ một chuỗi, người ta có thể sử dụng một here string, sử dụng<code>&#x3C;&#x3C;&#x3C;</code> : <syntaxhighlight lang="bash" inline="">tr a-z A-Z <<< "one two three"</syntaxhighlight> <span></span>, hoặc là: <syntaxhighlight lang="bash">
 
To read from a string, one can use a [[here string]], using the <code>&lt;&lt;&lt;</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==
== Đường ống ==
[[Tập tinImage:Pipeline.svg|thumb|A Mộtpipeline đườngof dẫnthree gồmprograms barun chươngon trình chạy trêna text terminal. ]]
CácPrograms chươngcan trìnhbe run thểtogether đượcsuch chạythat cùngone nhauprogram saoreads chothe mộtoutput chươngfrom trìnhanother đọcwith đầuno raneed từfor mộtan chươngexplicit trìnhintermediate khác mà không cần tệp trung gian rõ ràngfile. <syntaxhighlight lang="bash" inline="">command1 | command2</syntaxhighlight> <span></span> thực thiexecutes <tt>command1</tt>, sửusing dụngits đầuoutput raas củathe input làm đầu vào chofor <codett>command2</codett> (thườngcommonly đượccalled gọi[[Pipeline là đường ống(Unix)|piping]], với kýwith tựthe "|" đượccharacter gọibeing known as "pipe").
 
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.
Hai chương trình thực hiện các lệnh có thể chạy song song với không gian lưu trữ duy nhất là bộ đệm làm việc (Linux cho phép tối đa 64K cho mỗi bộ đệm) cộng với bất kỳ không gian làm việc nào mà mỗi lệnh xử lý yêu cầu. Ví dụ, lệnh "sort" không thể tạo ra bất kỳ đầu ra nào cho đến khi tất cả các bản ghi đầu vào đã được đọc, vì bản ghi cuối cùng nhận được có thể trở thành đầu tiên theo thứ tự được sắp xếp. Hệ điều hành thử nghiệm của Tiến sĩ Alexia Massalin, [[Synthesis kernel#Massalin.27s Synthesis kernel|Synthesis]], sẽ điều chỉnh mức độ ưu tiên của từng tác vụ khi chúng chạy theo mức độ đầy đủ của bộ đệm đầu vào và đầu ra.
 
This produces the same end result as using two redirects and a temporary file, as in:
Điều này tạo ra kết quả cuối cùng giống như sử dụng hai chuyển hướng và một tệp tạm thời, như cặp lệnh dưới đây: <syntaxhighlight lang="bash" line="1">
 
<syntaxhighlight lang="bash">
command1 > tempfile
command2 < tempfile
rm tempfile
</syntaxhighlight>
</syntaxhighlight> Nhưng ở đây, <code>command2</code> không bắt đầu thực thi cho đến khi <code>command1</code> kết thúc và một tệp tạm thời đủ lớn được yêu cầu để giữ kết quả trung gian cũng như bất kỳ không gian làm việc nào mà mỗi tác vụ yêu cầu. Ví dụ, mặc dù DOS cho phép cú pháp "pipe", nhưng nó sử dụng cách tiếp cận thứ hai này. Do đó, giả sử một số chương trình chạy trong thời gian dài, "Worker" tạo ra các thông báo khác nhau khi nó hoạt động và chương trình thứ hai, TimeStamp sao chép từng bản ghi từ ''stdin'' sang ''stdout'', thêm vào phía trước ngày và giờ của hệ thống khi nhận được bản ghi. Một chuỗi như <syntaxhighlight inline="" lang="bash">Worker | TimeStamp > LogFile.txt</syntaxhighlight> <span></span> sẽ chỉ điền thời gian khi Worker đã hoàn thành vào dòng đầu tiên, và ghi thời gian đọc và ghi tệp đầu ra của nó ở các dòng tiếp theo.
 
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.
 
MộtA good dụexample điểnfor hìnhcommand chopiping đườngis ống lệnh là kết hợpcombining <code>[[Echoecho (lệnhcommand)|echo]]</code> vớiwith mộtanother lệnhcommand khácto đểachieve đạtsomething đượcinteractive thứin a đó tương tác trong mộtnon-interactive shell không tương tác, ví dụe.g. <syntaxhighlight lang="bash" inline="">echo -e 'user\npass' | ftp localhost</syntaxhighlight> <span></span> . ĐiềuThis nàyruns chạy ứng dụng kháchthe [[FTPFile Transfer Protocol|ftp]] vớiclient with input <tt>user</tt> đầu vào, nhấnpress <tt>return</tt>, sau đóthen <tt>pass</tt> .
 
TrongIn sửcasual dụng thông thườnguse, bước đầuthe tiêninitial củastep mộtof đườnga ốngpipeline thườngis often <code>cat</code> hoặcor <code>echo</code>, đọcreading từfrom tệpa hoặcfile chuỗior string. ĐiềuThis nàycan thườngoften be thểreplaced đượcby thayinput thếindirection bằngor chỉ định đầu vào hoặca [[here string]], and sửuse dụngof cat and đườngpiping ốngrather thaythan input chuyểnredirection hướngis đầuknown vào được gọi làas [[Catuseless (Unix)|sửuse dụngof cat vô dụng]] . For dụ:example, cácthe lệnhfollowing saucommands: <syntaxhighlight lang="bash" line="1">
<syntaxhighlight lang="bash">
cat infile | cmd
echo $string | cmd
echo -e 'user\npass' | ftp localhost
</syntaxhighlight>
</syntaxhighlight> có thể được thay thế bởi: <syntaxhighlight lang="bash" line="1">
can be replaced by:
<syntaxhighlight lang="bash">
cmd < infile
cmd <<< $string
ftp localhost <<< $'user\npass'
</syntaxhighlight>
</syntaxhighlight> Vì <code>echo</code> thường là một lệnh shell nội bộ, nên việc sử dụng nó không bị chỉ trích như cat, là một lệnh bên ngoài.
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:
 
== Chuyển hướng đến và đi từ xử lí tệp tiêu chuẩn ==
Trong các shell Unix có nguồn gốc từ shell Bourne ban đầu, hai hành động đầu tiên có thể được sửa đổi thêm bằng cách đặt một số (bộ [[Đặc tả tập tin|mô tả tệp]] ) ngay trước [[Phân tích từ vựng|ký tự]] ; điều này sẽ ảnh hưởng đến luồng nào được sử dụng để chuyển hướng. Các luồng I / O tiêu chuẩn Unix là:
{| class="wikitable"
! Handle !! Name !! Description
! Xử lý
! Tên
! Sự miêu tả
|-
| 0
| [[Standard streams#Standard input (stdin)|stdin]] || Standard input
| stdin
| Đầu vào tiêu chuẩn
|-
| 1
| [[Standard streams#Standard output (stdout)|stdout]] || Standard output
| stdout
| Đầu ra tiêu chuẩn
|-
| 2
| [[Standard streams#Standard error (stderr)|stderr]] || Standard error
| stderr
| Lỗi tiêu chuẩn
|}
Ví dụ: <syntaxhighlight lang="bash" inline="">command1 2> file1</syntaxhighlight> <span></span> thực thi <tt>command1</tt>, hướng luồng lỗi tiêu chuẩn đến <code>file1</code>.
 
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>.
Trong các shell có nguồn gốc từ csh ( shell C ), cú pháp thay vào đó sẽ thêm ký tự <tt>&</tt> (ampersand) vào các ký tự chuyển hướng, do đó đạt được kết quả tương tự. Lý do cho điều này là để phân biệt giữa một tệp có tên '1' và stdout, tức là 'cat file 2> 1' so với 'cat file 2> &1'. Trong trường hợp đầu tiên, stderr được chuyển hướng đến một tệp có tên '1' và trong trường hợp thứ hai, stderr được chuyển hướng đến stdout.
 
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>.
Một khả năng hữu ích khác là chuyển hướng một xử lý tệp tiêu chuẩn sang một tệp khác. Biến thể phổ biến nhất là hợp nhất lỗi tiêu chuẩn thành đầu ra tiêu chuẩn để thông báo lỗi có thể được xử lý cùng với (hoặc thay thế cho) đầu ra thông thường. Ví dụ: <syntaxhighlight lang="bash" inline="">find / -name .profile > results 2>&1</syntaxhighlight> <span></span> sẽ cố gắng tìm tất cả các tệp có tên <tt>.profile</tt> . Nếu thực hiện mà không chuyển hướng, nó sẽ xuất các lần tìm được vào stdout và lỗi (ví dụ như thiếu đặc quyền đối với các thư mục được bảo vệ) vào stderr . Nếu đầu ra tiêu chuẩn được hướng đến tập tin <code>results</code>, thông báo lỗi xuất hiện trên console. Để xem cả lượt truy cập và thông báo lỗi trong tệp <code>results</code>, cần hợp nhất stderr (xử lý 2) vào stdout (xử lý 1) bằng cách sử dụng '''<tt>2> & 1</tt>''' .
 
NếuTo đầuwrite raboth đượcerrors hợpand nhấtstandard vàooutput đườngto ống''file'', đểthe chuyểnorder sangshould chươngbe trìnhreversed. Standard output would first be khácredirected to the file, chuỗithen hợpstderr nhấtwould tệpadditionally '''<tt>2>be &redirected 1</tt>'''to phảithe đặtstdout trướchandle that hiệuhas ống,already dobeen đó,changed to point at the file: <syntaxhighlight lang="bash" inline="">findcommand /> -name .profilefile 2>&1 | less</syntaxhighlight> <span></span> .
 
Một hình thức tuân thủ đơn giản nhưng không phải POSIX của lệnh, <syntaxhighlight lang="bash" inline="">command > file 2>&1</syntaxhighlight> <span></span> là (không có sẵn trong Bourne Shell trước phiên bản 4, bản phát hành cuối cùng hoặc trong vỏ shell Debian Almquist tiêu chuẩn được sử dụng trong Debian / Ubuntu): <syntaxhighlight lang="bash" inline="">command &>file</syntaxhighlight> <span></span> hoặc <syntaxhighlight lang="bash" inline="">command >&file</syntaxhighlight> <span></span> .
==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==
Có thể sử dụng <code>2>&1</code> trước " <code>></code> " nhưng kết quả thường bị hiểu sai. Quy tắc là bất kỳ chuyển hướng nào đều đặt tay cầm vào luồng đầu ra một cách độc lập. Vì vậy, " <code>2>&1</code> " đặt xử lý <code>2</code> thành bất cứ điều gì xử lý điểm<code>1</code> , mà tại thời điểm đó thường là ''stdout'' . Sau đó, " <code>></code> " chuyển hướng xử lý <code>1</code> sang một thứ khác, ví dụ như một tệp, nhưng nó '''không''' thay đổi xử lý <code>2</code>, mà vẫn trỏ đến ''stdout'' .
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==
Trong ví dụ sau, đầu ra tiêu chuẩn được ghi vào ''file'', nhưng lỗi được chuyển hướng từ stderr sang stdout, tức là được gửi đến màn hình: <syntaxhighlight lang="bash" inline="">command 2>&1 > file</syntaxhighlight> <span></span> .
*[[Here-document]], a way of specifying text for input in command line shells
*[[Shell shoveling]]
*[[Command substitution]]
*[[Process substitution]]
 
==External links==
Để ghi cả lỗi và đầu ra tiêu chuẩn vào ''tập file'', thứ tự phải được đảo ngược. Đầu ra tiêu chuẩn trước tiên sẽ được chuyển hướng đến tệp, sau đó stderr cũng sẽ được chuyển hướng đến stdout đã được thay đổi để trỏ đến tệp: <syntaxhighlight lang="bash" inline="">command > file 2>&1</syntaxhighlight> <span></span> . Windows PowerShell 5 định nghĩa sáu luồng khác nhau.
*{{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)}}
== Đường ống xích ==
[[Category:Articles with example code]]
Các mã thông báo chuyển hướng và đường ống có thể được nối lại với nhau để tạo ra các lệnh phức tạp. Ví dụ: <syntaxhighlight lang="bash" inline="">sort infile | uniq -c | sort -n > outfile</syntaxhighlight> <span></span> sắp xếp các dòng của <tt>infile</tt> theo thứ tự từ điển, viết các dòng duy nhất với tiền tố là số lần xuất hiện, sắp xếp các dòng theo số lần xuất hiện và ghi vào <tt>outfile</tt> . Kiểu xây dựng này được sử dụng rất phổ biến trong [[Câu lệnh shell|các tập lệnh shell]] và [[File batch|tập tin bó]] .
[[Category:DOS technology]]
[[Category:Unix software]]
[[Category:Unix]]
[[Category:Windows administration]]
 
[[pl:Standardowe strumienie]]
== Chuyển hướng đến nhiều đầu ra ==
Lệnh chuẩn <tt>tee</tt> có thể chuyển hướng đầu ra từ một lệnh đến một số địa điểm: <syntaxhighlight lang="bash" inline="">ls -lrt | tee xyz</syntaxhighlight> <span></span> . Điều này chỉ đạo đầu ra danh sách tập tin cho cả đầu ra tiêu chuẩn và tập tin <tt>xyz</tt> .
[[Category:Pages with unreviewed translations]]