brewedbits.dev

Personal blog with guides and news on selfhosting, Linux and AI, from the Netherlands

nextDash nextdash --aboutYour bookmarks. Your terminal. checks your links knows your Docker host one container, no cloudLive demo →nextdash.cc ↗

Tip: truncate -s 0 empties a log file that a program still has open

Linux
~/tips/tip-linux-truncate-s-0-empty-log

truncate -s 0 /var/log/app/debug.log

Free the space of a runaway log without deleting the file or restarting the program.

A log grows out of control and the disk is filling up. Deleting it with rm does not give the space back while the program still has the file open. Emptying it does.

truncate -s 0 /var/log/app/debug.log

-s 0 sets the size of the file to zero bytes. The file stays the same file, with the same owner and permissions, so the program keeps writing to it and the space is free right away. I would check df -h before and after to see the difference.

Many people use > file for the same job, and that works in most shells. truncate reads clearer in a script and can do several files at once, such as truncate -s 0 /var/log/app/*.log.

There is a catch with programs that do not open the log in append mode. They remember their position in the file, and their next write lands at that old offset. The file then gets its old size back as a sparse file with a hole full of zero bytes in front. ls -l shows a big size while du shows little space used. Programs that append, which most loggers do, start writing at zero.

Emptying the file throws the log away for good, so copy the part you still need first. For a permanent fix, give the log a logrotate rule instead of truncating by hand. And truncate can also make a file bigger: truncate -s 1G creates a sparse file of that size, so double check the number you type.

Further reading: truncate(1) manual page

More Linux tips a2query -m rewrite renice -n 10 -p 4242 cat config.yml | xsel -ib xvfb-run -a your-program --some-flag dpkg --get-selections > packages.txt All Linux tips (261) All topics

Link