0

I have a script that writes to a logfile like this:

$ nohup myscript.sh > myscript.out 2>&1 &

when the log file gets very large, I need to truncate it like this:

> myscript.out

I see the size go to 0 briefly but immediately jumps back to full size again.

$ ls -ald myscript.out
-rw-rw-r-- 1 vmware vmware 14285855 Apr 11 04:33 myscript.out
$ > myscript.out
$ ls -ald myscript.out
-rw-rw-r-- 1 vmware vmware 0 Apr 11 04:33 myscript.out
$ ls -ald myscript.out
-rw-rw-r-- 1 vmware vmware 14298778 Apr 11 04:33 myscript.out

How can I truncate it so the size goes to zero and starts growing again from zero?

I have tried many other alternatives but nothing works. Same thing, size goes to 0, then back to full size.

true > myscript.out
: > myscript.out
echo -n > myscript.out
cp /dev/null myscript.out
truncate -s 0 myscript.out
dd if=/dev/null of=myscript.out
4
  • One (or more) of the writers of the logfile is holding it open in append mode. The next time it writes to the file, the append is made where that open file descriptor remembers to seek to. The file has probably become sparse: you might check this by checking the blocks used (instead of the "file size") with du -h myscript.out. It might be usual to close a logfile on each append to flush it, or perhaps rotate it and remove older versions later. Apr 11, 2022 at 9:51
  • 1
    This is one reason why using redirected stderr or stdout for logging is a bad idea - the log file and how big it is becomes locked to your running process. There are good reasons why logging such as syslog is built into operating systems. You have to kill your running process, then clean up the log file. Apr 11, 2022 at 9:54
  • @Paul_Pedant, I think they'd need to be holding it open with a non-append fd, as a an append-mode fd would implicitly and automatically seek to the end on each write. But it's about a process holding an fd open anyway. (Ok, that's what Stéphane's answer in cat /dev/null > file.log does not truncate large file in Darwin of course also says.)
    – ilkkachu
    Apr 11, 2022 at 10:11
  • 1
    @ilkkachu Exactly so. I messed up that append-mode makes it append to the current size, and non-append makes it append to its private idea of where the size used to be. Apr 11, 2022 at 10:26

0

Browse other questions tagged .