Given a file, foo.txt:
1
2
3
4
5
Say we want to change it to contain:
1
2
3
Why does head -n3 foo.txt > foo.txt
leave foo.txt empty?
Given a file, foo.txt:
1
2
3
4
5
Say we want to change it to contain:
1
2
3
Why does head -n3 foo.txt > foo.txt
leave foo.txt empty?
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.
fork
andexec
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:19head
,sed
etc. are generally inline editors – Mateusz Jagiełło Feb 19 '13 at 18:19head
to the file, you could pipe it totee
as such:head -n3 foo.txt | tee foo.txt
.tee
won't write to the file until it receives the data fromhead
via the pipe. – Feb 19 '13 at 21:02tee
documented to only open the output file after it has received input? – Aaron McDaid Jul 05 '16 at 18:15