16

This question already has an answer here:

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?

marked as duplicate by Sergiy Kolodyazhnyy command-line Jan 13 '17 at 13:35

This question has been asked before and already has an answer. If those answers do not fully address your question, please ask a new question.

  • 3
    interesting question! – Pisu Jun 13 '12 at 6:07
23

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.

  • 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

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