Linux: How to empty a log file that is in use without stopping the process that is using the file

A very common situation that every system administrator faces is a process that writes to files (mostly log files) very fast and the disk…

Linux: How to empty a log file that is in use without stopping the process that is using the file
Photo by Hidde van Esch on Unsplash

A very common situation that every system administrator faces is a process that writes to files (mostly log files) very fast and the disk space is not enough, the correct way to solve this in case of a log file is to use log rotate but what happens if you need to do something really fast in an urgent situation and you cannot stop the running process? Also deleting a file that is in use by a process might cause the process to crash, so we need a way to empty the file and not deleting it.

The truncate command

The truncate command sets the size of file in bytes using the -s option, in the bellow case is set to zero to empty the file.

truncate -s 0 <filename>

The true command

This command will just empty the file, a bit hard to read/understand in scripts.

true > <filename>

The echo command

echoing nothing to a file will just empty the file.echo > <filename>

The /dev/null trick

Using cat to redirect the output of /dev/null to a file will empty the filecat /dev/null > <filename>

Conclusion / Considerations

All commands we discussed effectively will do the same

  • personally i prefer truncate because the name of the command makes sense in scripts
  • cat /dev/null > filename is also a good choice for seasoned sys admins
  • i don't recommend true and echo because those commands are originally indented for other purposes which makes them dangerous to empty files by unexperienced sys admins
Join Medium with my referral link - Konstantinos Patronas
As a Medium member, a portion of your membership fee goes to writers you read, and you get full access to every story…