Write a Safe Automation Script with Dry Run and Error Handling

Get a commented shell or Python script for your repetitive task, with a dry-run flag, clear error handling and a test command to try on sample files first.

You getPlan, script and how to run

Prompt

Prompt
Act as a senior automation engineer who writes small, safe scripts for people who are not full-time programmers.

Your job: write a shell or Python script that automates a repetitive task for me. Before writing any code, ask me these questions in one numbered message, then wait for my answers:
1. Which operating system and shell do I use, and is Python 3 installed?
2. What is the task, step by step, the way I do it by hand now?
3. What are the inputs (folders, file types, example names) and what should the output look like?
4. What must never happen (overwriting, deleting, touching certain folders)?

Rules:
- Include a --dry-run flag that prints every planned action without changing anything.
- Handle missing paths, permission errors and name collisions with a clear message; never overwrite or delete silently.
- Use only the standard library or built-in tools unless I agree to install something.
- Add a one-line plain-English comment above each block.
- Give a test command that creates 3-5 sample files in a temporary folder and runs the script on them.

Output format:
1. Plan (3-5 bullets)
2. Script (one code block)
3. How to run (dry run first, then real run)
4. Test command
5. Checks before using it on real files

End with one line listing your assumptions and any risk of data loss.

Example output

At a glanceHow the invoice sorting script runs safelyFrom dry run to verified real use on invoice PDFs
  1. Test on sample filesCreate 3 dated invoices and notes.txt in /tmp/inv_test
  2. Dry runRun with --dry-run to show actions only
  3. Read MOVE and SKIP linesConfirm only invoice files are listed
  4. Back up firstBack up Downloads or copy 10 real files to test
  5. Real runSame command without --dry-run
  6. Run it twiceSecond run should skip everything

Example for: a freelancer on macOS (zsh, Python 3.11) who moves invoice PDFs from Downloads into month folders by hand.

1. Plan
  • Find files matching invoice_*.pdf in the source folder
  • Read each file's modified date and build a YYYY-MM folder name
  • Move the file into that folder, creating it if needed
  • Skip and report any file that already exists at the target
2. Script
#!/usr/bin/env python3
"""Sort invoice PDFs into YYYY-MM folders by modified date."""
import argparse
import shutil
import sys
from datetime import datetime
from pathlib import Path

def main():
    # Read command-line options
    parser = argparse.ArgumentParser(description="Sort invoice PDFs by month.")
    parser.add_argument("source", help="Folder with the PDFs")
    parser.add_argument("dest", help="Folder for the month folders")
    parser.add_argument("--dry-run", action="store_true", help="Show actions only")
    args = parser.parse_args()
    src = Path(args.source).expanduser()
    dst = Path(args.dest).expanduser()

    # Stop early if the source folder is missing
    if not src.is_dir():
        sys.exit("Error: source folder not found: " + str(src))

    moved = skipped = 0
    for pdf in sorted(src.glob("invoice_*.pdf")):
        # Build the month folder name from the modified date
        month = datetime.fromtimestamp(pdf.stat().st_mtime).strftime("%Y-%m")
        target = dst / month / pdf.name

        # Never overwrite an existing file
        if target.exists():
            print("SKIP (already exists):", target)
            skipped += 1
            continue

        print("MOVE", pdf.name, "->", target)
        if not args.dry_run:
            try:
                target.parent.mkdir(parents=True, exist_ok=True)
                shutil.move(str(pdf), str(target))
            except PermissionError:
                print("ERROR (no permission):", pdf)
                skipped += 1
                continue
        moved += 1

    # Print a summary
    label = "Would move" if args.dry_run else "Moved"
    print(label, moved, "file(s); skipped", skipped)

if __name__ == "__main__":
    main()
3. How to run
  1. Dry run: python3 ~/scripts/sort_invoices.py ~/Downloads ~/Invoices --dry-run
  2. Read the MOVE and SKIP lines.
  3. Real run: same command without --dry-run.
4. Test command
mkdir -p /tmp/inv_test/in && cd /tmp/inv_test
touch -t 202403150900 in/invoice_1001.pdf
touch -t 202403280900 in/invoice_1002.pdf
touch -t 202404020900 in/invoice_1003.pdf
touch in/notes.txt
python3 ~/scripts/sort_invoices.py in out --dry-run
python3 ~/scripts/sort_invoices.py in out && ls -R out

Expected: out/2024-03 holds 1001 and 1002, out/2024-04 holds 1003, and notes.txt stays put.

5. Checks before real use
  • Confirm the dry run lists only invoice files
  • Back up Downloads once, or copy 10 real files to test
  • Run it twice to confirm the second run skips everything

Assumptions and risks: modified date matches the invoice month (re-downloaded files may not); files are moved, not copied, so test on copies first.

Written by AI from this prompt. Your results will vary.

Tips and common edits

Why this works

  • Asking for OS, inputs and forbidden actions first stops the model from guessing paths, shells or file patterns.
  • A required --dry-run flag and no-overwrite rule make the first run harmless, even for beginners.
  • The disposable test command proves the script works on fake files before it touches real data.

Use when you keep renaming, moving or converting files by hand. Have your OS, a few example file names and the result you want ready. Works in ChatGPT, Claude or Gemini.

Common edits

  • Ask for a PowerShell version if you are on Windows and cannot install Python.
  • Ask it to add a log file or a cron/Task Scheduler line so the script runs automatically.

Prompt details

By
Prompts-GPT editors
Published

Did this prompt work?

Keep exploring

More in Coding