Take the 2-minute tour ×
Ask Ubuntu is a question and answer site for Ubuntu users and developers. It's 100% free, no registration required.

I removed all files in a directory and then ran ls > foo in that same directory.

Running cat foo reveals that the newly created file "foo" contains "foo". Why is the file "foo" not empty? When ls executes, there are no files in the directory yet, right?

share|improve this question
3  
interesting question! –  Pisu Jun 13 '12 at 6:07

1 Answer 1

up vote 23 down vote accepted

The > command line directive happens before the ls command is executed. The shell has to be ready to save the output that the ls command may produce, so it has to create and open the file for writing.

When ls is executed by the shell, the foo file exists and hence ls outputs "foo" which is what you found in the file foo.

share|improve this answer
    
Ah, so in general, when using someCommand > fileName, the OS will create the new file first before executing someCommand. Thanks! –  David Faux Jun 10 '12 at 16:54
2  
If you don't like that, you can do something like ls | (sleep 2; cat > foo), where 2 is 2 seconds to wait before opening that file with cat. –  taneli Jun 14 '12 at 11:58

Your Answer

 
discard

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.