Linux Basic — Automation-Ready Scripts
Automation-Ready Scripts
Scripts designed for cron or systemd must run correctly without a human watching. That means no terminal, no $PATH assumptions, no interactive prompts.
The Checklist
| Requirement | Implementation |
|---|---|
| Non-interactive | No read, no prompts, no select |
| Absolute paths | #!/usr/bin/env bash or /bin/bash, full paths to commands |
Explicit $PATH |
Set PATH=/usr/local/bin:/usr/bin:/bin at top |
| Set strict mode | set -euo pipefail + trap for cleanup |
| Log everything | Redirect to a log file or use logger |
| Exit codes matter | Return 0 on success, nonzero on failure |
| Alert on failure | Email, Slack, PagerDuty when exit != 0 |
| Idempotent | Running twice doesn’t break things |
| Lock file | Prevent concurrent runs with flock |
Template
#!/usr/bin/env bash
set -euo pipefail
# explicit PATH
PATH=/usr/local/bin:/usr/bin:/bin
export PATH
LOGFILE="/var/log/myautomation.log"
LOCKFILE="/var/run/myautomation.lock"
log() { echo "$(date '+%F %T') $*" | tee -a "$LOGFILE"; }
die() { log "ERROR: $*"; exit 1; }
# prevent concurrent runs
exec 9>"$LOCKFILE"
flock -n 9 || die "already running"
trap 'rm -f "$LOCKFILE"' EXIT
log "starting"
# do work here
log "complete"
Use logger -t myautomation to send messages to syslog if you prefer centralized logs.
Idempotency
An idempotent script can run multiple times safely:
- Check if the target already exists before creating it
- Use
rsyncwith--updateinstead of blindly copying mkdir -pinstead ofmkdir
[[ -d /backup/latest ]] || mkdir -p /backup/latest
rsync -a --delete /data/ /backup/latest/
Alerting on Failure
Cron emails output by default (if mail is configured). For modern alerting:
# at end of script
if [[ $? -ne 0 ]]; then
curl -X POST https://hooks.slack.com/... -d '{"text":"backup failed"}'
fi
Or wrap the cron job:
0 2 * * * /opt/backup.sh || echo "backup failed" | mail -s "ALERT" ops@example.com
Next → Automated Backup Script