In Linux, from a bash shell, how can I print the contents of a file and remove the content I just printed content from the file?

I have a program writing texts to a file repeatedly. On a Linux shell prompt, I want to print the contents of the file and then delete the printed contents from the file. I want to do this repeatedly, to make my file size small enough.

Do we have bash command lines or combinations to do that?

  • 1
    So you want to add lines at the end of a file, and remove lines from the beginning? A file probably isn't the best data structure here. Would a pipe, or possibly a named pipe, be OK?
    – dhag
    Mar 27 '15 at 2:30

I want to print the contents of the file and then delete printed contents from the file

lpr file && truncate -s0 file
  • 1
    What about the data written between the time lpr finishes reading from the file and truncate truncates it. You'd want to suspend the process(es) of the writing application(s) first. Also what if the file is not open in O_APPEND mode by the writing application. Mar 27 '15 at 10:56
  • 1
    @StéphaneChazelas Yes. Before we can productively go further, I think the OP has to provide more information on what other process accesses this file, whether the access could be concurrent, whether suspending it is allowed, and whether it obeys any file-locking protocols.
    – John1024
    Mar 27 '15 at 23:49

For a regular file you can do:

while [ -s /path/to/file ] &&
      exec </path to file
do    dd bs=1k count=1
      dd bs=1k of=/path/to/file
  • 3
    That won't work properly in most cases as if the writing application has opened the file with O_APPEND, and writes while the second dd is running, their output will be intertwined. If it did not open with O_APPEND, then it will keep writing where it was at, so in the (now) middle of the file. bs=k is not standard, and not even documented where it does something (some versions of GNU dd) and not even self explanatory (I would expect it to be short of 0k while it seems to be 1k). Mar 27 '15 at 11:12
  • @StéphaneChazelas - this will ... print file content and delete printed content from file... I don't know of any way a person might tack on lines to the end of a file as this (or any other similarly intentioned process) simultaneously wrote the file. This would need suspending/stopping while the other process did the write - some kind of lockfile check could be worthwhile. If the fs understands file holes, dd could be used to greater effect with seek and notrunc to zero the portion just read, I suppose.
    – mikeserv
    Mar 27 '15 at 15:27

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.