why in an empty folder executing ls > empty.txt shows me empty.txt inside empty.txt ?

it is not poetry, it is true and I do not know why.

For me, they way to think ls > empty.txt is the following step by step:

  1. ls is executed, and I get the output (void at that very moment)
  2. > means I get the output of the previous command (actually fd 2)
  3. empty.txt is the name of the file that gets the output of ls (nothing).

So why running

cat empty.txt

I get


if the folder is empty?


Your ordering is wrong. Rather than have every program know how to redirect the output, the shell does the redirection.

So what happens is

  1. The shell starts a new shell to handle the command.
  2. The original shell waits for the new shell to finish.
  3. The new shell handles the > empty.txt, which involves creating the file.
  4. The new shell replaces itself with ls
  5. ls runs, listing the empty.txt file, and exits.
  6. The original shell is notified that the new shell, which has become ls, has finished and prints a new prompt.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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