Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Truncating a file while it's being used (Linux)

I have a process that's writing a lot of data to stdout, which I'm redirecting to a log file. I'd like to limit the size of the file by occasionally copying the current file to a new name and truncating it.

My usual techniques of truncating a file, like

cp /dev/null file 

don't work, presumably because the process is using it.

Is there some way I can truncate the file? Or delete it and somehow associate the process' stdout with a new file?

FWIW, it's a third party product that I can't modify to change its logging model.

EDIT redirecting over the file seems to have the same issue as the copy above - the file returns to its previous size next time it's written to:

ls -l sample.log ; echo > sample.log ; ls -l sample.log ; sleep 10 ; ls -l sample.log -rw-rw-r-- 1 user group 1291999 Jun 11  2009 sample.log -rw-rw-r-- 1 user group 1 Jun 11  2009 sample.log -rw-rw-r-- 1 user group 1292311 Jun 11  2009 sample.log 
like image 973
Hobo Avatar asked Jun 11 '09 09:06

Hobo


People also ask

How do I truncate a Linux log file?

You can simply truncate a log file using > filename syntax. For example if log file name is /var/log/foo, try > /var/log/foo as root user.

How does truncate work in Linux?

The truncate command is used to shrink or extend the size of a file to the given size. The truncate command cannot remove the file whereas removes the contents of the file and set size of file is zero byte. The meaning of truncate is reducing.

What happens when a file is truncated?

To truncate is to shorten by cutting off. In computer terms, when information is truncated, it is ended abruptly at a certain spot. For example, if a program truncates a field containing the value of pi (3.14159265...) at four decimal places, the field would show 3.1415 as an answer.


1 Answers

As of coreutils 7.0, there is a truncate command.

like image 92
Peter Eisentraut Avatar answered Sep 20 '22 21:09

Peter Eisentraut