Unix & Linux Stack Exchange is a question and answer site for users of Linux, FreeBSD and other Un*x-like operating systems. 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

This question already has an answer here:

Given a file, foo.txt:


Say we want to change it to contain:


Why does head -n3 foo.txt > foo.txt leave foo.txt empty?

share|improve this question

marked as duplicate by jasonwryan, uther, Renan, Stéphane Chazelas, Thor Feb 19 '13 at 23:51

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.

up vote 10 down vote accepted

This happens because the > redirection occurs before the head program is started. The > redirection truncates the file if it exist, so when the head is reading a file it is already empty.

share|improve this answer
Interesting. Do you have any detail on why it works this way? – cantlin Feb 19 '13 at 17:13
well, first bash (or the shell you are using) opens/creates the files it will use for redirection. Then it replaces the currently used file descriptors for stdin, stdout and stderr with the file descriptors it created for redirection as necessary. Then it executes the fork and exec system calls to start a new process thus the started process has the standard files redirected. Then bash restores its original file descriptors for itself. This is roughly what happens. – Serge Feb 19 '13 at 17:19
head, sed etc. are generally inline editors – Mateusz Jagiełło Feb 19 '13 at 18:19
Instead of redirecting the output of head to the file, you could pipe it to tee as such: head -n3 foo.txt | tee foo.txt. tee won't write to the file until it receives the data from head via the pipe. – Evan Teitelman Feb 19 '13 at 21:02
@EvanTeitelman, ? Is tee documented to only open the output file after it has received input? – Aaron McDaid Jul 5 at 18:15

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