Write a safe bash script header for a production maintenance script. What goes in it and why?
IntermediateScenarioScheduling, automation and scripting
Answer
Situation read → Fail fast, clean up, log.
What I'd do →
#!/usr/bin/env bash
set -Eeuo pipefail
IFS=$'\n\t'
trap 'echo "ERROR line $LINENO: $BASH_COMMAND" >&2' ERR
tmpdir=$(mktemp -d)
trap 'rm -rf "$tmpdir"' EXIT
log() { logger -t maint "$*"; echo "$(date -Is) $*"; }
Why → -e exits on error, -u catches unset variables, pipefail catches failures inside pipes, the ERR trap tells you where it died, and the EXIT trap always cleans up temp files.
Interview tip → Mention shellcheck in CI for every script.
More on Scheduling, automation and scripting
A database dump must run every night at 1:30 AM. How do you schedule it with cron so it is reliable?BeginnerConvert that nightly cron job to a systemd timer. Why would you?IntermediateA cron job runs every 5 minutes, but sometimes takes 8 minutes and two copies overlap, corrupting data. How do you prevent that?BeginnerYou have 300 servers running the same cron job at midnight, and they hammer a shared API. How do you fix it?IntermediateA job must run on the last day of every month. Cron has no "last day" field. What do you do?IntermediateYou inherited a server and need to know every scheduled job on it. Where do you look?Beginner