Why Deleting a Linux File Doesn’t Free Space – and How to Recover It
This guide shows how a file can appear deleted on Linux yet still occupy disk space, explains the inode reference‑count mechanism, demonstrates how to reproduce the issue with dd and a C program, and provides commands like lsof and /proc inspection to locate and release such hidden usage.
Observing disk usage of a file
Check mount usage with df -h. Create a 50 MiB file in /boot:
dd if=/dev/urandom of=/boot/test.txt bs=50M count=1Run df -h again to see increased used space.
Program that keeps the file open
#include <stdio.h>
#include <unistd.h>
int main(void) {
FILE *fp = fopen("/boot/test.txt", "rw+");
if (fp == NULL) {
perror("open file failed");
return -1;
}
while (1) {
sleep(1);
}
fclose(fp);
return 0;
}Compile and run:
gcc -o openFile openFile.c
./openFileThe program opens the file and loops forever, keeping the descriptor open.
Deleting the file while it is open
In another terminal execute rm /boot/test.txt. df -h shows that used space does not decrease because the process still holds a reference.
Space is released when the process exits
Terminate the program (e.g., Ctrl+C) and run df -h again; the free space returns to the original value.
Why the file is not removed
Linux removes a file only when its inode reference count reaches zero. The count includes the number of hard links and the number of open file descriptors. Opening a file increments i_count; rm only decrements the link count. As long as i_count > 0, the data blocks remain allocated.
struct inode {
unsigned long i_ino;
atomic_t i_count; /* reference count */
unsigned int i_nlink; /* hard‑link count */
/* other fields omitted */
};Finding deleted but still open files
List open descriptors that are marked deleted: lsof | grep deleted Or inspect a specific process: ls -l /proc/$(pidof openFile)/fd Entries such as 3 -> /boot/test.txt (deleted) indicate the file is still held open.
Practical advice
Always close file descriptors when they are no longer needed. Leaving files open after deletion can cause apparent disk‑space exhaustion, especially for log or temporary files.
Signed-in readers can open the original source through BestHub's protected redirect.
This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactand we will review it promptly.
Liangxu Linux
Liangxu, a self‑taught IT professional now working as a Linux development engineer at a Fortune 500 multinational, shares extensive Linux knowledge—fundamentals, applications, tools, plus Git, databases, Raspberry Pi, etc. (Reply “Linux” to receive essential resources.)
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.
