Why does "ls > foo" produce a file containing "foo"? [duplicate]

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?


Solution 1:

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.