exec operation file descriptor in linux

ringa_lee
Release: 2017-06-23 11:21:35
Original
2409 people have browsed it

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

Linux default file descriptor

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 command associated file descriptor

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
Copy after login

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

Note:

  1. echo "hello" >&4 to the file descriptor Only use > for input content, not >>. At this time, > will not clear the file.

  2. 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>&-
    Copy after login

    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!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!