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 →
- A single
logfunction 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 } LOG_LEVEL=DEBUG ./script.shturns on debug lines;TRACE=1turns onset -xwith a line-numberPS4.- 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.
More on Scenarios: writing and hardening scripts
You inherit a 600-line `deploy.sh` with no error handling. It "sometimes half-deploys". Where do you start?IntermediateA script with `#!/bin/sh` works on CentOS but fails on Ubuntu with `Syntax error: "(" unexpected`. What is going on and what do you do?BeginnerYou need a deploy script that humans and CI both call with `--env`, `--version` and `--dry-run`. How do you design its interface?BeginnerA maintenance script must run as the `deploy` user, never as root, because files it creates must be owned by `deploy`. How do you enforce that?BeginnerTen scripts in a repo each copy-paste their own `log`, `die`, retry and config loading. How do you fix this?IntermediateA script is run both by engineers and by cron. Cron logs are full of colour codes and the script sometimes hangs waiting for input. Fix it.Beginner