Can You please explain me why: 'cat < file.txt > file.txt ' makes file.txt empty ?
Because it opens and truncates the file before reading the data — it being shell, the redirections are processed by shell before even starting cat
.
The >
redirection happens first and opens file.txt
for writing which clears any existing content.
-
This answer is somewhat misleading -- @hacker's is more precise. On my systems, the redirections are processed in order of specification. That is,
<
happens first, and then>
, but the latter opens not merely "for writing" but with truncation (O_TRUNC
), which is what "clears existing content." @hacker is right, this happens beforecat(1)
is even executed. – pilcrow Feb 8 '10 at 22:20
file
) you could typecat <file.txt >>file.txt
as two >> mean appending to instead of deleting the file. – GregC Dec 22 '09 at 6:32