Posted on

Delete a file from the command line that’s still in use

I found myself taking over a few servers which had around 30 sites on them, all with hundreds of their own errors. I had a look in the /var/log directory and found the php5-fpm.log file was over 10GB in size! There are ways of easily truncating this but I found a particular issue which could help some of you. Deleting a large file that’s currently open on the server. A large file which is being used by the system can still remain in your memory. So when you delete your large file and expect your disk space to be free from that file, you’ll be disappointed when you run:

df -h

This command shows the server disk usage. Turns out, there is a process still running in the background which needs to be stopped until this can free up your memory.

To show the list of open files currently running on your server, you can use a simple command called lsof:

lsof -nP | grep '(deleted)'

We’re using the n and P flags and then just piping grep to show the deleted files. The flags used are as follows (taken from the man file):

-P inhibits the conversion of port numbers to port names for network files. Inhibiting the conversion may make lsof run a little faster. It is also useful when port name lookup is not working properly.

-n inhibits the conversion of network numbers to host names for network files. Inhibiting conversion may make lsof run faster.  It is also useful when host name lookup is not working properly.

This will return the files currently deleted that are still in use. Take note of the key (you can check this if you run lsof -nP at the top). The second column shows the process ID. To remove this, simply kill it using:

kill 1234

Where 1234 will be your process ID.

After a quick check using:

df -h

You’ll see that your disk space is now free!