Search code examples
linuxshelltee

Looking for something like "tee" but which open/closes the target file with each write?


I've got something like mycommand | tee -a mylogfile.log but because the log file resides on a disk which might be getting remounted over and over, I want to have tee open/close the file with each write (say, e.g. with each line). Is there a way to accomplish something like this?


Solution

  • This will open and close mylogfile.log with each line:

    mycommand | while IFS= read -r line; do printf "%s\n" "$line" | tee -a mylogfile.log; done
    

    With bash, this can be slightly simplified:

    mycommand | while IFS= read -r line; do tee -a mylogfile.log <<<"$line"; done