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

A long script needs useful logs: levels, timestamps, and a debug mode that does not require editing the code. Design it.

BeginnerScenarioScenarios: writing and hardening scripts
Answer

Situation read → Logs must be greppable and the level must be controllable at runtime.

What I'd do →

  1. A single log function writing to stderr:
    LOG_LEVEL=${LOG_LEVEL:-INFO}
    declare -A _lvl=([DEBUG]=10 [INFO]=20 [WARN]=30 [ERROR]=40)
    log() {
      (( _lvl[$1] >= _lvl[$LOG_LEVEL] )) || return 0
      printf '%s %-5s [%s] %s\n' "$(date -u +%FT%TZ)" "$1" "${0##*/}" "${*:2}" >&2
    }
    
  2. LOG_LEVEL=DEBUG ./script.sh turns on debug lines; TRACE=1 turns on set -x with a line-number PS4.
  3. Under systemd, rely on the journal; elsewhere, also send to syslog with logger -t.

Why → Uniform, leveled logs make incidents answerable with grep and journalctl instead of guesswork.

Interview tip → Mention logging to stderr so stdout stays clean for data.

All Shell Scripting questions Roadmap: Shell scripting (Bash)

More on Scenarios: writing and hardening scripts