Delete open files. When df and du show different results.
- siwy
- maj, 17, 2023
- Linux
- No Comments
In Linux systems, files that have been deleted but are still open by some process can sometimes take up valuable disk space. Fortunately, there’s a way to handle this issue.
Here’s a command that allows you to “clean” these files:
find /proc/*/fd -ls | grep '(deleted)' | awk '{print $11}' | xargs -I % sh -c 'echo /dev/null > %'
Understanding what this command does requires breaking it down into parts. Let’s start from the beginning.
The find /proc/*/fd -ls
command searches all files in the /proc/*/fd
directories. The /proc/*/fd
directory contains files representing open file descriptors for every process. The -ls
option makes find
display detailed information about each found file.
Then grep '(deleted)'
filters the results from the previous command, looking for lines that contain the phrase (deleted)
. This phrase appears in ls
results for files that have been deleted but are still open by some process.
Next, awk '{print $11}'
prints the 11th field (understood as strings of characters separated by spaces) from each line. In the context of ls
results, this field contains the file path.
Finally, xargs -I % sh -c 'echo /dev/null > %'
executes a command for each file path, redirecting the content of /dev/null
(which is an empty file) to the file at the given path. This essentially “cleans” the file – its content is replaced with an empty file.
In conclusion, this command allows you to find open but deleted files on your system and then “clean” these files. It’s a very useful tool for managing disk space, especially in situations where a process still maintains open file descriptors for files that have been deleted.
However, remember that this command can be dangerous if you’re not sure what it does. It’s always worth understanding commands before you start using them on your system.
More useful commands: https://github.com/PBujakiewicz/linux-cheat-sheet