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.
forkandexecsystem 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,sedetc. are generally inline editors – Mateusz Jagiełło Feb 19 '13 at 18:19headto the file, you could pipe it toteeas such:head -n3 foo.txt | tee foo.txt.teewon't write to the file until it receives the data fromheadvia the pipe. – Feb 19 '13 at 21:02teedocumented to only open the output file after it has received input? – Aaron McDaid Jul 05 '16 at 18:15