Goal
A script that does one server task reliably, stops cleanly on any error, and never deletes or overwrites more than it should.
Inputs
- The task in plain words: [e.g. compress logs older than 7 days in /var/log/myapp and delete archives older than 30 days]
- Operating system and shell: [e.g. Ubuntu 24.04, Bash 5]
- Paths, users and tools available: [e.g. rsync, tar, gzip; runs as a service user, not root]
- How often it runs: [e.g. daily at 02:30 by cron]
- Where output should go: [log file path, email, or standard output only]
Steps
- Start with a shebang and strict mode: set -euo pipefail, and a safe IFS.
- Parse arguments, including --dry-run and --help, and validate every path before use.
- Take a lock with flock so two runs never overlap.
- Do the work, logging each step with a timestamp; in dry-run, print actions instead of running them.
- Trap errors and exit with a non-zero code and a clear message.
Output format
- The full script in one fenced code block, with short comments above each section.
- A usage line and two example commands, one with --dry-run.
- The crontab line, with output redirected to the log.
- A test checklist: empty folder, missing folder, no permission, disk full, and a second run while the first is still going.
Check before answering
- Every variable is quoted, and rm or find -delete only ever runs on a checked, non-empty path.
- No passwords or tokens in the script; read them from an environment variable or a protected file.
- Commands used exist on the stated system, with no GNU-only flags if the target is not GNU.






