Say I have some process which pipes to a file:

yes > foo

I now want to clear/empty the file foo, but still want the process to write to the file, i.e. start filling the file again after clearing.

Is this possible?

  • First write of your new batch should be ">" instead of ">>" and it will clear previous information...or just rm -f <file> – Gravy Mar 9 '16 at 15:57
  • @Gravy: Does not work. No new file is created. – knub Mar 9 '16 at 16:00
  • @downvoter: Care to explain? – knub Mar 9 '16 at 16:00
  • can you provide the surrounding script so we know exactly what is trying to be accomplished? – Gravy Mar 9 '16 at 16:01
  • 2
    Try yes >> foo instead of yes > foo and do > foo separately to clear the file – iruvar Mar 9 '16 at 16:08

Use yes >> foo instead of yes > foo and separately :>foo to clear the file

yes >> foo cause read to open foo with O_APPEND. This causes the file offset to be positioned at the end of the file before each write.

So yes writes to the file foo, with each write causing the file pointer to be positioned at the end of foo. Meanwhile : > foo truncates the file to 0 bytes. Now the next yes write, due to the re-positioning of file pointer at the "end" of the zero-byte foo induced by O_APPEND, starts over at the beginning of the zero-byte foo

| improve this answer | |

If you do yes > foo and do it again, it does remove any content that was in the file foo after the first execution...

You can use one of the following:

rm foo
yes > foo

> foo
yes > foo

echo "" > foo
yes > foo
| improve this answer | |

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.