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.

    1. 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.
    2. 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.
    3. 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.
    4. 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 du one 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:

    1. Scan a specified path, aggregate space usage by directory (including subdirectories), and sort the results.
    2. List the N largest files along with their modification times.
    3. Identify common cleanup candidates, such as expired logs and temporary files.
    4. 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, /var itself, 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:

    1. Recursively aggregate usage per directory (including subdirectories), sort by size, and list the 20 largest files with modification times.
    2. Cleanup targets only .log and .tmp files modified more than 30 days ago; operations are allowed only within the directory specified by --clean-dir.
    3. Default to dry-run; delete only when --execute is passed. Require typing yes before deletion, and confirm each file over 10GB individually.
    4. Output complete, runnable code using argparse, with exception handling and permission error messages; do not omit the main function.
    5. 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.

    1. #!/usr/bin/env python3
    2. """Disk space analysis and safe cleanup tool (example). Dry-run by default; deletion requires --execute."""
    3. import argparse
    4. import heapq
    5. import os
    6. import stat
    7. import sys
    8. import time
    9. from collections import defaultdict
    10. from pathlib import Path
    11. SAFE_SUFFIXES = {".log", ".tmp"} # Whitelisted suffixes
    12. MIN_AGE_DAYS = 30 # Only clean files modified more than 30 days ago
    13. CONFIRM_SIZE = 10 * 1024 ** 3 # Files over 10GB require individual confirmation
    14. PROTECTED = {Path(p) for p in ("/", "/bin", "/boot", "/dev", "/etc",
    15. "/lib", "/proc", "/root", "/sbin", "/sys",
    16. "/usr", "/var")}
    17. def human(n):
    18. for unit in ("B", "KB", "MB", "GB", "TB"):
    19. if n < 1024:
    20. return f"{n:.1f}{unit}"
    21. n /= 1024
    22. return f"{n:.1f}PB"
    23. def fmt_time(ts):
    24. return time.strftime("%Y-%m-%d", time.localtime(ts))
    25. def is_within(path: Path, base: Path) -> bool:
    26. try:
    27. path.relative_to(base)
    28. return True
    29. except ValueError:
    30. return False
    31. def check_clean_scope(clean_dir: Path, root: Path):
    32. if clean_dir in PROTECTED or os.path.ismount(clean_dir):
    33. sys.exit(f"Refusing to clean a protected path or mount point: {clean_dir}")
    34. if not is_within(clean_dir, root):
    35. sys.exit("--clean-dir must be inside the analysis path")
    36. def same_device(path, dev):
    37. try:
    38. return os.lstat(path).st_dev == dev
    39. except OSError:
    40. return False
    41. def scan(root: Path):
    42. root_dev = os.lstat(root).st_dev
    43. dir_size = defaultdict(int) # Directory -> recursive total size
    44. files = [] # (size, path, mtime)
    45. seen = set() # Hard links already counted (device, inode)
    46. errors = []
    47. def on_error(err):
    48. errors.append(err.filename)
    49. for dirpath, dirnames, filenames in os.walk(root, onerror=on_error):
    50. # Do not descend into other disk partitions; os.walk does not follow symlinks by default
    51. dirnames[:] = [d for d in dirnames
    52. if same_device(os.path.join(dirpath, d), root_dev)]
    53. base = Path(dirpath)
    54. for name in filenames:
    55. fp = base / name
    56. try:
    57. st = os.lstat(fp)
    58. except OSError:
    59. errors.append(str(fp))
    60. continue
    61. if not stat.S_ISREG(st.st_mode):
    62. continue # Skip symlinks, device files, sockets, etc.
    63. if st.st_nlink > 1:
    64. key = (st.st_dev, st.st_ino)
    65. if key in seen:
    66. continue # Count the same data only once
    67. seen.add(key)
    68. files.append((st.st_size, fp, st.st_mtime))
    69. d = base # Accumulate size to the containing directory and all parents
    70. while True:
    71. dir_size[d] += st.st_size
    72. if d == root or d == d.parent:
    73. break
    74. d = d.parent
    75. return dir_size, files, errors
    76. def report(dir_size, files, top):
    77. print(f"\n== Top {top} directories by usage (including subdirectories) ==")
    78. for d, size in sorted(dir_size.items(), key=lambda x: x[1], reverse=True)[:top]:
    79. print(f"{human(size):>10} {d}")
    80. print(f"\n== Largest {top} files ==")
    81. for size, fp, mtime in heapq.nlargest(top, files, key=lambda f: f[0]):
    82. print(f"{human(size):>10} {fmt_time(mtime)} {fp}")
    83. def find_candidates(files, clean_dir: Path):
    84. cutoff = time.time() - MIN_AGE_DAYS * 86400
    85. hits = [(size, fp, mtime) for size, fp, mtime in files
    86. if fp.suffix.lower() in SAFE_SUFFIXES
    87. and mtime < cutoff
    88. and is_within(fp, clean_dir)]
    89. return sorted(hits, key=lambda x: x[0], reverse=True)
    90. def clean(candidates, execute: bool):
    91. total = sum(size for size, _, _ in candidates)
    92. print(f"\n== Cleanup candidates: {len(candidates)} files, {human(total)} total ==")
    93. for size, fp, mtime in candidates:
    94. print(f"{human(size):>10} {fmt_time(mtime)} {fp}")
    95. if not execute:
    96. print("\n[Dry run] No files were deleted. After confirming the list, run again with --execute.")
    97. return
    98. if input("\nType yes to confirm deletion of the files above: ").strip() != "yes":
    99. print("Cancelled. No files were deleted.")
    100. return
    101. deleted, freed = 0, 0
    102. for size, fp, _ in candidates:
    103. if size > CONFIRM_SIZE:
    104. ans = input(f"{fp} is over 10GB. Confirm deletion? [y/N] ").strip().lower()
    105. if ans != "y":
    106. print(f"Skipped: {fp}")
    107. continue
    108. try:
    109. os.remove(fp)
    110. deleted += 1
    111. freed += size
    112. except PermissionError:
    113. print(f"Permission denied, skipped: {fp}")
    114. except OSError as e:
    115. print(f"Deletion failed: {fp} ({e})")
    116. print(f"\nDone: deleted {deleted} files, freed {human(freed)}.")
    117. def main():
    118. parser = argparse.ArgumentParser(description="Disk space analysis and safe cleanup")
    119. parser.add_argument("path", help="Root directory to analyze, e.g. /data/logs")
    120. parser.add_argument("--clean-dir",
    121. help="Directory allowed for deletion; must be inside path; defaults to path")
    122. parser.add_argument("--top", type=int, default=20, help="Show top N items, default 20")
    123. parser.add_argument("--execute", action="store_true",
    124. help="Actually delete files; dry-run by default")
    125. args = parser.parse_args()
    126. try:
    127. root = Path(args.path).resolve(strict=True)
    128. except FileNotFoundError:
    129. sys.exit(f"Path does not exist: {args.path}")
    130. if not root.is_dir():
    131. sys.exit(f"Not a directory: {root}")
    132. clean_dir = (Path(args.clean_dir).resolve(strict=True)
    133. if args.clean_dir else root)
    134. check_clean_scope(clean_dir, root)
    135. print(f"Scanning {root} ...")
    136. dir_size, files, errors = scan(root)
    137. report(dir_size, files, args.top)
    138. if errors:
    139. print(f"\nNote: {len(errors)} paths could not be read (permission issues, etc.) and were skipped.")
    140. candidates = find_candidates(files, clean_dir)
    141. clean(candidates, args.execute)
    142. if __name__ == "__main__":
    143. 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.

    1. mkdir -p /tmp/clean_test/app/logs
    2. truncate -s 200M /tmp/clean_test/app/logs/old.log
    3. touch -d "40 days ago" /tmp/clean_test/app/logs/old.log
    4. truncate -s 11G /tmp/clean_test/app/big.tmp
    5. touch -d "45 days ago" /tmp/clean_test/app/big.tmp
    6. touch /tmp/clean_test/app/new.log # New file, should not appear in candidates
    7. # Step 1: Analyze and dry-run without deleting anything
    8. python3 clean.py /tmp/clean_test --clean-dir /tmp/clean_test/app
    9. # Step 2: After confirming the candidate list, actually delete
    10. python3 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.