|
Linux Redirection is to modify some of the original default, the original system commands to change the default implementation, such as simple I do not want to see the output of the display but want to output to a file can be redirected through Linux To carry out this work.
Linux default input is the keyboard, the output is the display. You can use redirection to change these settings. For example, when using the wc command was to manually enter a text to calculate the number of characters, with a redirect can be directly after a written file with the '< ' point to this command, you can directly statistics on this file Characters and so on. Output is the same, you can redirect the output of the screen to a file, and then to the file to see the results. Redirection operator can be used to command input and output data stream from the default location to redirect to other locations, the location of the input or output data stream is called the handle; common handle there are three, of course, the handle can be extended, the general OS Provide similar functionality. Handle Handle Code handle Description
STDIN 0 Keyboard input
STDOUT 1 Outputs information to the prompt window
STDERR 2 Outputs an error message to the prompt window
The default < redirection input operator is 0, and the default> redirection output operator is 1. After you type the < or> operator, you must specify the location of the data to read or write, either a file name or another existing handle.
To specify redirection to an existing handle, use the & handle, followed by the & handle (which is the & handle number) to be redirected.
For example, the following command redirects handle 2 (that is, STDERR) to handle 1 (that is, STDOUT): 2> & 1
The following table lists the operators available for redirecting input and output data streams:
Linux redirection operator function description
> Write command output to a file or device, not a command prompt or handle
Read the command input from a file rather than from a keyboard or handle
>> Add the command output to the end of the file without deleting the information already in the file
> & Writes the output of one handle to the input of another handle
< & Reads an input from one handle and writes it to another handle output
| Read the output from a command and write it to the input of another command; also known as the pipe operator
Now we look back at the above phrase mysh> mylog.txt 2> & 1 can understand:
> Mylog.txt means that the standard output is redirected to mylog.txt, which is equivalent to mysh 1> mylog.txt;
2> & 1 means that the error output will be redirected to the standard output of a handle; Mysh command together is generated during the implementation of the standard output and error output will be redirected to mylog.txt;
Redirection function is very powerful, interested can go to try a variety of different combinations, look at the position before and after the change will have what results?
At some point we may not want to record what the standard output or error output, it can be used mysh> null 2> null or mysh> / dev / null 2> / dev / null;
Detailed I / O redirection
1, the basic concept (which is behind the understanding of the premise of knowledge, be sure to understand)
A, I / O redirection is usually related to FD, shell FD is usually 10, that is, 0 ~ 9;
B, commonly used FD 3, 0 (stdin, standard input), 1 (stdout, standard output), 2 (stderr, standard error output), default and keyboard, monitor, monitor;
C, use the < to change the read data channel (stdin), so that read from the specified file;
D, with the> to change the sent data channel (stdout, stderr), so that output to the specified file;
E, 0 is the default value of < , so < and 0 < are the same; Similarly,> and 1> is the same;
F, in the IO redirect, stdout and stderr pipeline will be ready before reading from the stdin data;
G, pipe "|" (pipe line): stdout on a command received the next command stdin;
H, tee command is not affect the original I / O, the stdout copy to a file to;
I, bash (ksh) The process of executing the command: Analysis command - Variable evaluation - Command substitution ( `` and $ ()) - Redirection - Wildcard expansion - Determine path - Execute command;
J, () will command group placed in the sub-shell to perform, also known as nested sub-shell, it is a very important feature is: inherit the parent shell's Standard input, output, and error plus any other open file descriptors.
K, exec command: commonly used to replace the current shell and restart a shell, in other words, there is no promoter sub-shell. Any existing environment will be cleared when using this command. Exec in the operation of the document descriptors, and only then, exec will not cover your current shell environment.
2, the basic IO
Cmd> file Redirect stdout to the file file;
Cmd >> file Redirect stdout to the file file (append);
Cmd 1> fiel to stdout redirect to the file file;
Cmd> file 2> & 1 stdout and stderr together to redirect to the file file;
Cmd 2> file to stderr redirect to the file file;
Cmd 2 >> file Redirect stderr to the file (append);
Cmd >> file 2> & 1 Redirect stderr and stderr to the file file (append);
Cmd < file> file2 cmd command to file the file as stdin to file2 file as stdout;
Cat < > file to read and write the way to open file;
Cmd < file cmd command to file file as stdin;
Cmd < < delimiter Here document, read from stdin until delimiter delimiters are encountered.
3, advanced IO
> & N uses the system call dup (2) to copy the file descriptor n and uses the result as standard output;
< & N Standard input copy from file descriptor n;
< & - Turns off standard input (keyboard);
> & - off the standard output;
N < & - that will be No. n input is turned off;
N> & - indicates that the output of No. n is turned off;
All of the above forms can be preceded by a number, the establishment of the document descriptors at this time designated by the figures instead of the default 0 or 1. Such as:
... 2> file Runs a command and directs the error output (file descriptor 2) to file.
... 2> & 1 Runs a command and combines its standard output and output. (Strictly speaking, file descriptor 2 is created by copying file descriptor 1, but the effect is usually to merge two streams.)
FD2 = FD1, FD2 does not mean that the value is equal to the value of FD1, because> is to change the data sent out of the channel, that is to say FD2 "data output channel", that is to say, To "data output channel" of FD1. If so, this change seems to have no effect, because FD2 default output and FD1 default output would have been monitor, the same! However, when FD1 is other files, or even other FD, this has a special purpose. Please be sure to understand this point.
Exec 0exec 1> outfilename # Open the file outfilename as stdout.
Exec 2> errfilename # Open the file errfilename as stderr.
Exec 0 < & - # Turn off FD0.
Exec 1> & - # to close FD1.
Exec 5> & - # Turn off FD5.
1 COMMAND_OUTPUT>
2 # redirect stdout to a file.
3 # If there is no document on the creation, or to cover.
4
5 ls -lR> dir-tree.list
6 # Create a file that contains a list of directory trees.
7
8:> filename
9 #> truncates the file "filename" to zero length.
10 # If the file does not exist, then create a 0-length file (the same as 'touch').
11 #: is a placeholder that does not produce any output.
12
13> filename
14 #> will truncate the file "filename" to zero length.
15 # If the file does not exist, then create a 0-length file (the same as 'touch').
16 # (same as ":>" above, but may not work under some shells.)
17
18 COMMAND_OUTPUT >>
19 # redirect stdout to a file.
20 # If the file does not exist, then create it, if there is, then append to the file behind.
twenty one
twenty two
23 # single-line redirection command (only affects the line they are in):
twenty four # ------------------------------------------------ --------------------
25
26 1> filename
27 # Redirect stdout to the file "filename".
28 1 >> filename
29 # Redirect and appends stdout to the file "filename".
30 2> filename
31 # Redirect stderr to the file "filename".
32 2 >> filename
33 # Redirect and append stderr to the file "filename".
34 & gt; filename
35 # redirect both stdout and stderr to the file "filename".
36
37 # ================================================ ===============================
38 # redirect stdout, one line at a time.
39 LOGFILE = script.log
40
41 echo "This statement is sent to the log file, \" $ LOGFILE \ "." 1> $ LOGFILE
42 echo "This statement is appended to \" $ LOGFILE \ "." 1 >> $ LOGFILE
43 echo "This statement is also appended to \" $ LOGFILE \ "." >> LOGFILE
44 echo "This statement is echoed to stdout, and will not appear in \" $ LOGFILE \ ".
45 # After each line, these redirection commands are automatically "reset".
46
Gt;
48
49 # redirect stderr, one line at a time.
50 ERRORFILE = script.errors
51
52 bad_command1 2> $ ERRORFILE # Error message sent to the $ ERRORFILE.
53 bad_command2 2 >> $ ERRORFILE # Error message added to $ ERRORFILE.
54 bad_command3 # Error message echo to stderr,
55 # + and does not appear in $ ERRORFILE.
56 # After each line, these redirection commands will automatically "reset".
57 # ================================================ ===============================
58
59
60
61 2> & 1
62 # redirect stderr to stdout.
63 # get the same error message as stdout and send it to one place.
64
65 & gt;
66 # redirects the file descriptors i to j.
67 # points to the output of all the documents are sent to j to j.
68
69> & j
70 # Default, redirect file descriptor 1 (stdout) to j.
71 # All the output passed to stdout is sent to j.
72
73 0 < FILENAME
74 < FILENAME
75 # Accept input from file.
76 # and ">" are pairs of commands, and are usually used in combination.
77 #
78 # grep search-word < filename
79
80
81 [j] < > filename
To read and write "filename", the file "filename" is opened, and the file descriptor "j" is assigned to it.
83 # If the file "filename" does not exist, create it.
84 # If the file descriptor "j" is not specified, then the default is fd 0, stdin.
85 #
86 # This application is usually written to a file specified in the place.
87 echo 1234567890> File # Write the string to "File".
88 exec 3 < > File # Opens "File" and assigns fd 3 to it.
89 read -n 4 < & 3 # Read only 4 characters.
90 echo -n.> & 3 # Write a decimal point.
91 exec 3> & - # Close fd 3.
92 cat File # ==> 1234.67890
93 # Random storage.
94
95
96
97 |
98 # pipeline.
Generic Purpose Handling and Command Chain Tools.
100 # is very similar to ">", but is actually more generic.
101 # is useful when trying to concatenate commands, scripts, files, and programs.
102 cat * .txt | sort | uniq> result-file
103 # For all the output of the. Txt file to sort, and delete duplicate rows,
104 # Save the result to "result-file".
You can combine multiple instances of the input and output redirection and / or pipe together to write on a single line.
Command < input-file> output-file
Command1 | command2 | command3> output-file
Multiple output streams can be redirected to a single file.
1 ls -yz >> command.log 2> & 1
2 # Put the result of the error option "yz" in the file "command.log".
3 # Because stderr is redirected to this file,
4 # + All the error messages are also pointing there.
5
Note that the following example does not give the same result.
7 ls -yz 2> & 1 >> command.log
8 # prints an error message, but does not write to the file.
9
10 # If both stdout and stderr are redirected,
11 # The order of the commands is slightly different.
The exec < filename command redirects stdin to a file, starting with the input from the file, rather than the standard input (usually the keyboard input). Read the file, and you can use sed and / or awk to analyze each line.
Use exec to redirect standard input
1 #! / Bin / bash
2 # Use 'exec' to redirect the standard input.
3
4
5 exec 6 < & 0 # The file descriptor # 6 and stdin link.
6 # saved stdin.
7
8 exec < data-file # stdin is replaced by the file "data-file".
9
10 read a1 # Read the first line of the file "data-file".
11 read a2 # Read the second line of the file "data-file".
12
13 echo
14 echo "Following lines read from file."
15 echo "-------------------------------"
16 echo $ a1
17 echo $ a2
18
19 echo; echo; echo
20
21 exec 0 < & 6 6 < & -
22 # Now restore stdin from fd # 6, because we just redirect stdin to # 6,
23 # + Then close fd # 6 (6 < & -), so that the descriptor continues to be used by other processes.
twenty four #
25 # < & 6 6 < & - This can be done.
26
27 echo -n "Enter data"
28 read b1 # Now "read" has returned to normal, is read from the stdin.
29 echo "Input read from stdin."
30 echo "----------------------"
31 echo "b1 = $ b1"
32
33 echo
34
35 exit 0 Use exec to redirect stdout 1 #! / Bin / bash
2 # reassign-stdout.sh
3
4 LOGFILE = logfile.txt
5
6 exec 6> & 1 # Connect fd # 6 to stdout.
7 # Save stdout.
8
9 exec> $ LOGFILE # stdout was replaced by the file "logfile.txt".
10
11 # ------------------------------------------------ ----------- #
12 # In this block all the output of the command are sent to the file $ LOGFILE.
13
14 echo -n "Logfile:"
15 date
16 echo "-------------------------------------"
17 echo
18
19 echo "Output of \" ls -al \ "command"
20 echo
21 ls-al
22 echo; echo
23 echo "Output of \" df \ "command"
24 echo
25 df
26
27 # ------------------------------------------------ ----------- #
28
29 exec 1> & 6 6> & - # restore stdout, and then close file descriptor # 6.
30
31 echo
32 echo "== stdout now restored to default =="
33 echo
34 ls-al
35 Echo
36
37 exit 0
-------------------------------------------------- ------------------------------
-------------------------------------------------- ------------------------------
Use exec to redirect stdin and stdout 1 #! / Bin / bash in the same script
2 # upperconv.sh
3 # Converts a specified input file to uppercase.
4
5 E_FILE_ACCESS = 70
6 E_WRONG_ARGS = 71
7
8 if [! -r "$ 1"] # to determine the specified input file is readable?
9 then
10 echo "Can not read from input file!"
11 echo "Usage: $ 0 input-file output-file"
12 exit $ E_FILE_ACCESS
13 fi # Even if the input file ($ 1) is not specified
14 # + will still exit with the same error (why?).
15
16 if [-z "$ 2"]
17 then
18 echo "Need to specify output file."
19 echo "Usage: $ 0 input-file output-file"
20 exit $ E_WRONG_ARGS
21 fi
twenty two
twenty three
24 exec 4 < & 0
25 exec < $ 1 # will be read from the input file.
26
27 exec 7> & 1
28 exec> $ 2 # will be written to the output file.
29 # Suppose the output file is writable (add check?).
30
31 # -----------------------------------------------
32 cat - | tr a-z A-Z # Convert to uppercase.
33 # ^^^^^ # Read from stdin. Reads from stdin.
34 # ^^^^^^^^^^ # Writes to stdout.
35 # However, both stdin and stdout are redirected.
36 # -----------------------------------------------
37
38 exec 1> & 7 7> & - # Restore stout.
39 exec 0 < & 4 4 < & - # Restore stdin.
40
41 # After recovery, the following line of code will print to stdout as expected.
42 echo "File \" $ 1 \ "written to \" $ 2 \ "as uppercase conversion."
43
44 exit 0
-------------------------------------------------- ------------------------------
I / O redirection is a way to avoid awkward sub-shell inaccessible variable problem.
-------------------------------------------------- ------------------------------
Avoid sub-shell 1 #! / Bin / bash
2 # avoid-subshell.sh
3 # Matthew Walker's recommendations.
4
5 Lines = 0
6
7 echo
8
9 cat myfile.txt | while read line; # (Translator's Note: pipeline will produce sub-shell)
10 do {
11 echo $ line
12 ((Lines ++)); # Increase the value of this variable
13 # + but the external loop can not access.
14 # Sub-shell problem.
15}
16 done
17
18 echo "Number of lines read = $ Lines" # 0
19 # Error!
20
21 echo "------------------------"
twenty two
twenty three
24 exec 3 < > myfile.txt
25 while read line < & 3
26 do {
27 echo "$ line"
28 ((Lines ++)); # Increase the value of this variable
29 # + Now the external loop can be accessed.
30 # No sub-shell, now no problem.
31}
32 done
33 exec 3> & -
34
35 echo "Number of lines read = $ Lines" # 8
36
37 echo
38
39 exit 0
40
41 # The following line is the result of the script, the script will not come here.
42
43 $ cat myfile.txt
44
45 Line 1.
46 Line 2.
47 Line 3.
48 Line
49 Line 5.
50 Line 6.
51 Line 7.
52 Line 8.
|
|
|
|