Linux cat example

3

Can You please explain me why: 'cat < file.txt > file.txt ' makes file.txt empty ?

josipBros

Posted 2009-12-21T22:44:26.530

Reputation:

Just to add to the bottom two answers: if you wanted to make a loop (endlessly filling file) you could type cat <file.txt >>file.txt as two >> mean appending to instead of deleting the file. – GregC – 2009-12-22T06:32:13.950

Yikes. That's just scary. I've never even thought of using (abusing?) cat and pipes like that! That's why we have the "touch" command. ;-) Makes for a cool example though. – Brian Knoblauch – 2010-01-06T20:29:20.547

Answers

16

Because it opens and truncates the file before reading the data — it being shell, the redirections are processed by shell before even starting cat.

Michael Krelin - hacker

Posted 2009-12-21T22:44:26.530

Reputation: 626

13

The > redirection happens first and opens file.txt for writing which clears any existing content.

Gregory Pakosz

Posted 2009-12-21T22:44:26.530

Reputation: 562

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 before cat(1) is even executed. – pilcrow – 2010-02-08T22:20:21.457