Script Explanation: deleted_fd_cleanup.sh
This script helps identify and optionally truncate files that have been deleted but are still held open by processes on a Linux system (commonly causing df to show full disk while du shows much less).
Features
- Detects all (deleted) files currently held open by processes using lsof.
- Ensures each PID+FD is handled only once to avoid duplicate operations.
- Can run in two modes:
- Dry-run
[--dry-run]
(default): Shows which files would be truncated and their sizes without making any changes. - Prune
[--prune]
: Actually truncates the files, freeing disk space.
- Displays:
- PID and file descriptor (FD) path
/proc/<pid>/fd/<fd>
- File size in human-readable form and in bytes
- Total size of all deleted files at the end
How It Works
- Uses lsof to list deleted files.
- Parses PID and FD using awk.
- Checks if the
/proc/<pid>/fd/<fd>
exists. - Truncates the file if in prune mode.
- Accumulates the total size of all deleted files.
- Prints per-file info and total space held by deleted files.
Usage
- Dry-run (default)
./deleted_fd_cleanup.sh
- Shows which deleted files are still held open and their sizes.
- Does not modify any files.
- Example output:
Would truncate /proc/30853/fd/62 size: 2.3G bytes: 2411724800
Would truncate /proc/31110/fd/1811 size: 500M bytes: 524288000
TOTAL space of deleted files: 2.78 MB
- Explicit dry-run
./deleted_fd_cleanup.sh --dry-run
- Same as above; explicitly specifies dry-run mode.
- Prune (truncate)
./deleted_fd_cleanup.sh --prune
- Truncates all deleted files that are still held open, freeing disk space.
- Prints per-file info and total space freed.
- Example output:
Truncated /proc/30853/fd/62 size: 2.3G bytes: 2411724800
Truncated /proc/31110/fd/1811 size: 500M bytes: 524288000
TOTAL space of deleted files: 2.78 MB
Notes / Warnings
- Safe to use on log or temporary files.
- Do not truncate critical database or index files; it may corrupt the process.
- Always consider running dry-run first before pruning.
- Uses sudo because lsof and
/proc/<pid>/fd/
require root permissions.