Truncating a file in use

Here’s a nice trick to zero out a file that’s in use:

cat /dev/null > /path/to/file

The reason for this is that if you simply remove a file that’s in use by some process on the system, the disk space will not be released until the process closes the file or terminates.

By cating /dev/null and redirecting it to the file, it magically guts out the contents of the file while keeping the same inode. The process that has that file open will continue writing to it without knowing any better, and the disk space will be released.

Update: A simple test using python to keep a file handle open showed me that while the cat trick zeros out the file, python keeps track of the last position written to within the file. The next time the python process writes to the file, you’ll end up with null bytes at the beginning of the file.


Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )


Connecting to %s