Interview Prep/Shell Scripting/Scenarios: writing and hardening scripts

A nightly job should post to Slack when it starts, succeeds or fails, including the duration and the last 20 log lines on failure. Design it.

IntermediateScenarioScenarios: writing and hardening scripts
Answer

Situation read → Notifications must work even when the job crashes, so they belong in traps, not at the end of the happy path.

What I'd do →

log=$(mktemp); exec > >(tee -a "$log") 2>&1
start=$SECONDS
notify() { jq -n --arg t "$1" '{text: $t}' |
  curl -fsS --max-time 10 -H 'Content-Type: application/json' --data-binary @- "$SLACK_WEBHOOK" >/dev/null || true; }
finish() {
  local rc=$?
  if (( rc == 0 )); then notify "backup OK in $((SECONDS - start))s"
  else notify "backup FAILED (exit $rc) after $((SECONDS - start))s"$'\n'"$(tail -n 20 "$log")"; fi
  rm -f -- "$log"
}
trap finish EXIT
notify "backup started on $(hostname -s)"
  1. Build JSON with jq so log lines with quotes cannot break the payload.
  2. Notification failures must never fail the job (|| true).

Why → The EXIT trap sees the real exit code in all cases, including set -e aborts.

Interview tip → Mention avoiding alert fatigue: notify on failure and on recovery, and keep "started" messages for jobs people actively watch.

All Shell Scripting questions Roadmap: Shell scripting (Bash)

More on Scenarios: writing and hardening scripts