Every open file in Linux will be associated with a file descriptor. When needed, we can use the exec command to specify a number greater than 3 as the file
Every time it is opened A shell will open the default three file descriptors 0, 1, and 2, which represent standard input, standard output, and standard error output respectively.
exec 5>/tmp/a.txt reading method
exec 5exec 5<> ;/tmp/a.txt Read and write mode
exec 5<&-;exec5>&- Close the file descriptor
Application case: Reassociate the standard output in the shell script to record the log to the specified File
#!/bin/bash exec 4>&1 #用4记录标准输出 exec 1>/tmp/abc #重定向标准输出 echo "123" echo "456" exec 1>&4 #恢复标准输出 exec 4>&- #关闭4
Run this script, the echo output in the script will be output to the /tmp/abc file
The second line of the script uses 4>&1 to record the file descriptor of the standard output for convenience after execution. To restore standard output, you can also use exec 1>/dev/tty
echo "hello" >&4 to the file descriptor Only use > for input content, not >>. At this time, > will not clear the file.
Whether to clear the file needs to be determined when the exec command associates the file descriptor to the file. Use > or >>,
For example, there is the following script:
#!/bin/bash exec 4>/tmp/abc echo "123" >&4 echo "456" >&4 exec 4>&-
The content of the /tmp/abc file after each execution of the script is 123\n456
If the second line If you change to exec 4>>/tmp/abc, it will be appended
The clearing operation of the file is performed during the operation of the exec command
The above is the detailed content of exec operation file descriptor in linux. For more information, please follow other related articles on the PHP Chinese website!