introduce
File descriptors are integers associated with file input and output. When writing scripts, standard file descriptors are often used to redirect content output. 0, 1, and 2 are file descriptors (corresponding to stdin, stdout, stderr respectively ), < , >, >> are called operators.
concept
stdin(0): Standard input, this concept is a bit difficult to understand For example: 1. Use < to read content from the file, 2. The current command pipes the content to the next command and the next command, and the actual content is The transmission is to stdin so the next command also reads from stdin.
stdout(1): Standard output; this is the default option. How to use: 1> is equivalent to > or 1>> is equivalent to >>; if you want to use other file descriptors, you must put the file descriptor before the operator.
stderr(2): standard error, using method 2> or 2>>, standard error can insert error information into the file without displaying it in the terminal.
<: read content from file.
>: Insert content into the file, and the file content will be cleared before each insertion.
>>: Insert content into a file, append content to the end of an existing file.
example
Generate test data
echo "hello word" > test1 cp test1 test2 chmod 000 test2
stdin(0)
1. Read content from text
cat <test1
2. Pipe the read content to the next command
cat test1 |tr -t 'a-z' 'A-Z' >test1.new
stdin(1)
redirect content to file
echo "this is stdout 1" >std1
Append content to file
stderr(2)
When an error is reported, the terminal will display an error. You can write the error message to a file to prevent the terminal from displaying it.
Insert both stderr and stdout information into the file at the same time, use &
Direct error messages to standard output
echo "name" 2>&1 >> a or echo "name" >> a 2>&1
Redirect script internal text block, cat <<EOF>>log.txt EOF
custom file descriptor
Custom file descriptors also need to use exec; < , >, >> means the same as explained above, when calling a custom descriptor, you need to add & before the custom descriptor.
1. Customize stdin, define 3 as stdin to read content from the file, and then call 3. The result of calling 3 is the same as calling the file directly, which is similar to assignment.
exec 3<test1
2. Customized stdout, the test results found that using > in the custom descriptor to repeatedly write data to the file will not clear the previous content, but it will be cleared and rewritten in the standard descriptor.
Summarize
File descriptors are used very frequently in scripts, and the commonly used methods are standard output and standard error.
Personally collected learning routes and notes https://mp.weixin.qq.com/s/KQx_eIwdjCj3QdErxKb7ZQ