Ask Ubuntu is a question and answer site for Ubuntu users and developers. Join them; it only takes a minute:

Sign up
Here's how it works:
  1. Anybody can ask a question
  2. Anybody can answer
  3. The best answers are voted up and rise to the top

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
interesting question! – Pisu Jun 13 '12 at 6:07
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
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


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.