Shell scripts, cron and timers
Goal
A script that fails cleanly, and a scheduled job that really runs.
Skeleton
#!/bin/bash
set -euo pipefail
LOG=/var/log/myscript.log
main() {
local target="${1:?usage: $0 <target>}"
echo "$(date -Is) start $target" >> "$LOG"
if ! test -d "$target"; then
echo "$(date -Is) ERROR: $target missing" >> "$LOG"
return 1
fi
tar czf "/backup/$(basename "$target")-$(date +%F).tgz" "$target"
echo "$(date -Is) ok" >> "$LOG"
}
main "$@"
Controls
[ -d /data ] && [ -w /data ] || exit 1
case "$1" in start|stop) ;; *) echo "usage: $0 start|stop"; exit 2;; esac
for f in /etc/*.conf; do [ -e "$f" ] || continue; done
while read -r line; do echo "$line"; done < list.txt
Codes: 0 success, 1 generic failure, 2 bad usage.
cron
crontab -e
crontab -l
SHELL=/bin/bash
PATH=/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin
30 2 * * * /usr/local/bin/backup.sh /srv >> /var/log/backup.log 2>&1
/etc/cron.d/myjob has one extra field: the username. cron.allow/cron.deny control access.
systemd timer (more robust)
/etc/systemd/system/backup.service:
[Unit]
Description=Nightly backup
[Service]
Type=oneshot
ExecStart=/usr/local/bin/backup.sh /srv
/etc/systemd/system/backup.timer:
[Unit]
Description=Every night at 02:30
[Timer]
OnCalendar=*-*-* 02:30:00
Persistent=true
[Install]
WantedBy=timers.target
systemctl enable --now backup.timer
systemctl list-timers
Verify
bash -n /usr/local/bin/backup.sh
systemctl list-timers --all | head -4