Disk Full? How to Write a Safe Cleanup Script with a Lightweight Model
This article explains when lightweight language models are a good fit for coding tasks and walks through a real-world disk cleanup scenario. It covers a structured prompt design approach, a complete Python script with dry-run mode, whitelisted file suffixes, age-based filtering, and multi-layer safety checks, plus a test workflow using sparse files. Readers will learn how to generate a practical, safety-first cleanup tool with a lightweight model and validate it before running it against production data.
What Kind of Code Are Lightweight Models Good For?
Many developers assume that bigger models with longer reasoning traces write better code. But the high-frequency tasks of everyday programming don’t need that. Writing a data processing script, completing a piece of business logic, or debugging a single error message requires fast, direct, and good-enough answers. A multi-minute reasoning process adds little to these tasks and slows down the workflow.
When choosing a model, consider four dimensions.
- Response speed: This includes first-token latency and tokens per second. Interactive programming is a high-frequency question-and-answer process, and slow output interrupts your train of thought.
- Reasoning restraint: Some models produce long derivations for a simple string-processing request, much of which is unrelated to the final code. Tasks with clear goals are better served by concise answers.
- First-pass success rate: Can a single prompt produce code that runs directly? A model that requires repeated rework may take longer overall than one that gets it right the first time.
- Context understanding: Can it understand colloquial requests like “the disk is full, help me write an analysis and cleanup tool” and fill in reasonable default designs?
Lightweight models usually perform well on the first three dimensions. Reasoning overhead is low, answers come quickly, and success rates on standardized tasks are decent. An economical approach is: use a stronger model for solution design, use a lightweight model to generate the specific script, then use the stronger model for review.
| Task | Recommended model | Reason |
|---|---|---|
| Solution design, boundary analysis | Stronger model | Requires weighing risks and trade-offs |
| Generating specific scripts | Lightweight model | Fast response, high success rate on standardized tasks |
| Code review, security checks | Stronger model | Needs to find subtle logic flaws |
| Debugging a single error | Try lightweight model first | Switch to a stronger model if it fails |
These judgments should be confirmed with your own data. Record the time and rework count for several typical tasks before deciding whether to switch models.
A Real Scenario: Emergency Response to a Full Disk
Suppose a 1TB disk on a development machine or server is completely full. Builds fail, logs can’t be written, and applications start throwing errors. Troubleshooting runs into several difficulties:
- Directory hierarchies are deep, and running
duone by one is inefficient. - Large files are scattered across log directories, temp directories, and cache directories.
- Deletion is risky, so you must look carefully before acting.
This kind of problem is well suited to a lightweight model generating a script. An ideal script should have the following capabilities:
- Scan a specified path, aggregate space usage by directory (including subdirectories), and sort the results.
- List the N largest files along with their modification times.
- Identify common cleanup candidates, such as expired logs and temporary files.
- Provide a dry-run mode that lists what will be deleted before you confirm and execute.
In practice, follow a fixed order. First analyze and confirm where the usage comes from. Then do a dry run and check whether the candidate file list matches expectations. Next, test in a small directory only. Finally, proceed with actual deletion only after confirming that backups exist or files can be recovered.
Define the cleanup scope in advance. The following reference list should be adjusted for your own environment.
- Consider cleaning: application log directories (such as
/data/app/logs), build caches, package manager caches, and temporary directories you created yourself. - Do not clean:
/etc,/boot,/usr,/varitself, the system disk root, database data directories, and mount points themselves. For mount points, choose a subdirectory as the cleanup scope.
The whitelist validation in the script should match this list. Even if the script gets a path wrong, system directories won’t be deleted.
Prompt Design: The Constraints Behind a Single Sentence
A “one-sentence prompt” works because, although short, it contains key constraints. Here is a counterexample and an improved version.
Counterexample: “Help me figure out what to do when the disk is full.”
This sentence doesn’t specify the language, the functional scope, or safety requirements. The model will likely output an rm -rf command, or a script with no dry-run protection.
Improved version:
Write a disk space analysis and cleanup tool in Python 3. Requirements:
- Recursively aggregate usage per directory (including subdirectories), sort by size, and list the 20 largest files with modification times.
- Cleanup targets only
.logand.tmpfiles modified more than 30 days ago; operations are allowed only within the directory specified by--clean-dir.- Default to dry-run; delete only when
--executeis passed. Require typingyesbefore deletion, and confirm each file over 10GB individually.- Output complete, runnable code using argparse, with exception handling and permission error messages; do not omit the main function.
- Do not concatenate shell commands, do not follow symbolic links during traversal, and do not cross mount points.
This prompt contains seven elements: language, functionality, output form, safety switch, cleanup scope, interactive confirmation, and code completeness. Translating vague requirements into structured constraints is the key to getting usable code in one pass. If the first output isn’t ideal, add constraints first—for example, “switch to iterative traversal to avoid excessive memory usage”—rather than vaguely asking it to “rewrite it.”
If the model provides only fragments, explicitly ask it to complete the main function and list the missing parts so it can fill them in one by one.
Core Script Implementation
Below is a sample skeleton covering analysis, dry run, whitelist, 30-day filtering, and secondary confirmation. Its purpose is to illustrate the structure; do not use it in a real environment before validating it in a test directory.
#!/usr/bin/env python3"""Disk space analysis and safe cleanup tool (example). Dry-run by default; deletion requires --execute."""import argparseimport heapqimport osimport statimport sysimport timefrom collections import defaultdictfrom pathlib import PathSAFE_SUFFIXES = {".log", ".tmp"} # Whitelisted suffixesMIN_AGE_DAYS = 30 # Only clean files modified more than 30 days agoCONFIRM_SIZE = 10 * 1024 ** 3 # Files over 10GB require individual confirmationPROTECTED = {Path(p) for p in ("/", "/bin", "/boot", "/dev", "/etc","/lib", "/proc", "/root", "/sbin", "/sys","/usr", "/var")}def human(n):for unit in ("B", "KB", "MB", "GB", "TB"):if n < 1024:return f"{n:.1f}{unit}"n /= 1024return f"{n:.1f}PB"def fmt_time(ts):return time.strftime("%Y-%m-%d", time.localtime(ts))def is_within(path: Path, base: Path) -> bool:try:path.relative_to(base)return Trueexcept ValueError:return Falsedef check_clean_scope(clean_dir: Path, root: Path):if clean_dir in PROTECTED or os.path.ismount(clean_dir):sys.exit(f"Refusing to clean a protected path or mount point: {clean_dir}")if not is_within(clean_dir, root):sys.exit("--clean-dir must be inside the analysis path")def same_device(path, dev):try:return os.lstat(path).st_dev == devexcept OSError:return Falsedef scan(root: Path):root_dev = os.lstat(root).st_devdir_size = defaultdict(int) # Directory -> recursive total sizefiles = [] # (size, path, mtime)seen = set() # Hard links already counted (device, inode)errors = []def on_error(err):errors.append(err.filename)for dirpath, dirnames, filenames in os.walk(root, onerror=on_error):# Do not descend into other disk partitions; os.walk does not follow symlinks by defaultdirnames[:] = [d for d in dirnamesif same_device(os.path.join(dirpath, d), root_dev)]base = Path(dirpath)for name in filenames:fp = base / nametry:st = os.lstat(fp)except OSError:errors.append(str(fp))continueif not stat.S_ISREG(st.st_mode):continue # Skip symlinks, device files, sockets, etc.if st.st_nlink > 1:key = (st.st_dev, st.st_ino)if key in seen:continue # Count the same data only onceseen.add(key)files.append((st.st_size, fp, st.st_mtime))d = base # Accumulate size to the containing directory and all parentswhile True:dir_size[d] += st.st_sizeif d == root or d == d.parent:breakd = d.parentreturn dir_size, files, errorsdef report(dir_size, files, top):print(f"\n== Top {top} directories by usage (including subdirectories) ==")for d, size in sorted(dir_size.items(), key=lambda x: x[1], reverse=True)[:top]:print(f"{human(size):>10} {d}")print(f"\n== Largest {top} files ==")for size, fp, mtime in heapq.nlargest(top, files, key=lambda f: f[0]):print(f"{human(size):>10} {fmt_time(mtime)} {fp}")def find_candidates(files, clean_dir: Path):cutoff = time.time() - MIN_AGE_DAYS * 86400hits = [(size, fp, mtime) for size, fp, mtime in filesif fp.suffix.lower() in SAFE_SUFFIXESand mtime < cutoffand is_within(fp, clean_dir)]return sorted(hits, key=lambda x: x[0], reverse=True)def clean(candidates, execute: bool):total = sum(size for size, _, _ in candidates)print(f"\n== Cleanup candidates: {len(candidates)} files, {human(total)} total ==")for size, fp, mtime in candidates:print(f"{human(size):>10} {fmt_time(mtime)} {fp}")if not execute:print("\n[Dry run] No files were deleted. After confirming the list, run again with --execute.")returnif input("\nType yes to confirm deletion of the files above: ").strip() != "yes":print("Cancelled. No files were deleted.")returndeleted, freed = 0, 0for size, fp, _ in candidates:if size > CONFIRM_SIZE:ans = input(f"{fp} is over 10GB. Confirm deletion? [y/N] ").strip().lower()if ans != "y":print(f"Skipped: {fp}")continuetry:os.remove(fp)deleted += 1freed += sizeexcept PermissionError:print(f"Permission denied, skipped: {fp}")except OSError as e:print(f"Deletion failed: {fp} ({e})")print(f"\nDone: deleted {deleted} files, freed {human(freed)}.")def main():parser = argparse.ArgumentParser(description="Disk space analysis and safe cleanup")parser.add_argument("path", help="Root directory to analyze, e.g. /data/logs")parser.add_argument("--clean-dir",help="Directory allowed for deletion; must be inside path; defaults to path")parser.add_argument("--top", type=int, default=20, help="Show top N items, default 20")parser.add_argument("--execute", action="store_true",help="Actually delete files; dry-run by default")args = parser.parse_args()try:root = Path(args.path).resolve(strict=True)except FileNotFoundError:sys.exit(f"Path does not exist: {args.path}")if not root.is_dir():sys.exit(f"Not a directory: {root}")clean_dir = (Path(args.clean_dir).resolve(strict=True)if args.clean_dir else root)check_clean_scope(clean_dir, root)print(f"Scanning {root} ...")dir_size, files, errors = scan(root)report(dir_size, files, args.top)if errors:print(f"\nNote: {len(errors)} paths could not be read (permission issues, etc.) and were skipped.")candidates = find_candidates(files, clean_dir)clean(candidates, args.execute)if __name__ == "__main__":main()
Before running the code, create test data in a test directory to validate it. The commands below use truncate to create sparse files, which won’t actually fill up the disk.
mkdir -p /tmp/clean_test/app/logstruncate -s 200M /tmp/clean_test/app/logs/old.logtouch -d "40 days ago" /tmp/clean_test/app/logs/old.logtruncate -s 11G /tmp/clean_test/app/big.tmptouch -d "45 days ago" /tmp/clean_test/app/big.tmptouch /tmp/clean_test/app/new.log # New file, should not appear in candidates# Step 1: Analyze and dry-run without deleting anythingpython3 clean.py /tmp/clean_test --clean-dir /tmp/clean_test/app# Step 2: After confirming the candidate list, actually deletepython3 clean.py /tmp/clean_test --clean-dir /tmp/clean_test/app --execute
The dry-run output should list only old.log and big.tmp. new.log is less than 30 days old, so it won’t be listed. big.tmp exceeds 10GB, so it triggers an individual confirmation before deletion.
The operational sequence in a real environment is the same as in testing: analyze first, then dry-run, then trial in a small directory, and only then add --execute for the official directory. Before running, also confirm that backups exist or that deleted files can be recovered another way.
FAQ
What is a dry-run?
A dry-run means rehearsing without executing. The script lists all files that would be deleted and the total size, but does not modify the disk. This script defaults to dry-run; deletion only happens when --execute is explicitly added.
How do you avoid accidental deletion?
The script has five layers of protection. First, it defaults to dry-run. Second, it only handles whitelisted suffixes (.log and .tmp). Third, it only handles files modified more than 30 days ago. Fourth, --clean-dir must be inside the analysis path and cannot be a system directory or mount point. Fifth, deletion requires typing yes, and files over 10GB require individual confirmation. These protections are enforced at the code level and do not rely on the user’s memory.
How should the whitelist be configured?
Modify SAFE_SUFFIXES, MIN_AGE_DAYS, and PROTECTED at the top of the script. If certain logs need to be retained longer, increase MIN_AGE_DAYS or exclude the corresponding directory from --clean-dir. The whitelist should be as short as possible; each time you add a file type, validate it in a test directory first.
