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

Ten scripts in a repo each copy-paste their own `log`, `die`, retry and config loading. How do you fix this?

IntermediateScenarioScenarios: writing and hardening scripts
Answer

Situation read → Duplicated helpers drift apart; a fix in one script never reaches the others.

What I'd do →

  1. Create lib/common.sh with the shared functions, a # shellcheck shell=bash directive, and a double-source guard ([[ -n ${_COMMON_LOADED:-} ]] && return 0).
  2. Source it relative to the script, not the current directory:
    SCRIPT_DIR=$(dirname -- "$(readlink -f -- "${BASH_SOURCE[0]}")")
    # shellcheck source=../lib/common.sh
    source "$SCRIPT_DIR/../lib/common.sh"
    
  3. Keep the library free of side effects: only function definitions and defaults, no set -e, no exit at load time (callers own their strict mode).
  4. Prefix library functions and locals (opskit_init, _try) to avoid collisions and dynamic-scoping bugs.
  5. Add bats tests for the library itself, and configure .shellcheckrc with source-path=SCRIPTDIR.

Why → A tested library turns ten inconsistent scripts into ten thin scripts with one well-understood core.

Interview tip → Mention the dynamic-scoping trap: a library retry with local n silently breaks a caller's function that uses a global n.

All Shell Scripting questions Roadmap: Shell scripting (Bash)

More on Scenarios: writing and hardening scripts