Why reading and writing the same file through I/O redirection results in an empty file in Unix?

前端 未结 4 1734
抹茶落季
抹茶落季 2020-12-11 04:16

If I redirect output of a command to same file it reads from, its contents is erased.

sed \'s/abd/def/g\' a.txt > a.txt

Can anyone expla

4条回答
  •  孤城傲影
    2020-12-11 05:04

    The redirection operations <, >, etc. are handled by the shell. When you give a command to the shell that includes redirection, the shell will first open the file. In the case of > the file will be opened for writing, which means it gets truncated to zero size. After the redirection files have been opened, the shell starts a new process, binding its standard input, output, and error to any possible redirected files, and only then executes the command you gave. So when the sed command in your example begins execution, a.txt has already been truncated by the shell.

    Incidentally, and somewhat tangentially, this is also the reason why you cannot use redirection directly with sudo because it is the shell that needs the permissions to open the redirection file, not the command being executed.

提交回复
热议问题