shellunixio-redirection

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


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 explain why?


Solution

  • The first thing the redirection does is to open the file for writing, thus clearing any existing contents. sed then tries to read this empty file you have just created, and does nothing. The file is then closed, containing nothing.