Linux file descriptors and redirection, operators and redirection
Introduction
The file descriptor is an integer associated with the file input and output. When writing a script, the standard file descriptor is often used to redirect the content to the output, 0, 1, and 2 are file descriptors (corresponding to stdin, stdout, and stderr respectively). <,>,> is called operators.
Concept
Stdin (0): standard input. This concept is not easy to understand, for example: 1. use <read content from the file, 2. the current command transmits the content to the next command through a pipeline and the next command, while the actual content is transmitted to stdin, so the next command also reads the content from stdin.
Stdout (1): standard output; this is the default option. Usage: 1> equivalent to>Or1> equivalent to>. If you want to use another file descriptor, you must put the file descriptor before the operator.
Stderr (2): standard error. Use method 2> or 2>. you can insert the error message to a file rather than display it on the terminal.
<: Read content from the file.
>: Inserts content into a file. The file content is cleared before each insert.
>>: Insert the content to the file and append the content to the end of the existing file.
Instance
Generate Test Data
echo "hello word" > test1cp test1 test2chmod 000 test2
Stdin (0)
1. Read content from text
cat <test1
2. Transfer the read content to the next command through a pipeline
cat test1 |tr -t 'a-z' 'A-Z' >test1.new
Stdin (1)
Redirect content to a file
echo "this is stdout 1" >std1
Append content to a file
Stderr (2)
When an error is reported, the terminal displays an error. You can write the error information to a file to prevent the terminal from displaying it.
Insert both stderr and stdout information to the file &
Redirection script text block, cat <EOF> log.txt EOF
Custom file descriptor
The user-defined file descriptor also needs to use exec; <, >>>>, which means the same as described above. when calling the User-Defined descriptor, you must add & before the User-Defined descriptor &.
1. Customize stdin to define 3 as stdin to read content from the file, and then you can call 3. Calling 3 is the same as directly calling the file, which is somewhat similar to assigning values.
exec 3<test1
2. custom stdout. Test results show that using> repeat data to a file in the Custom descriptor does not clear the previous content, but the standard descriptor is cleared and then written.
Summary
File descriptors are frequently used in scripts. commonly used methods are standard output and standard errors.
Note: Author: pursuer. chen Blog: http://www.cnblogs.com/chenmh All essays on this site are original. You are welcome to repost them. However, you must indicate the source of the article and clearly give the link at the beginning of the article. Welcome to discussion |