Take the 2-minute tour ×
Super User is a question and answer site for computer enthusiasts and power users. It's 100% free, no registration required.

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

share|improve this question

migrated from stackoverflow.com Dec 21 '09 at 23:07

This question came from our site for professional and enthusiast programmers.

    
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 Dec 22 '09 at 6:32
    
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 Jan 6 '10 at 20:29
add comment

2 Answers

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

share|improve this answer
add comment

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

share|improve this answer
    
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 Feb 8 '10 at 22:20
add comment

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.