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 →
- Create
lib/common.shwith the shared functions, a# shellcheck shell=bashdirective, and a double-source guard ([[ -n ${_COMMON_LOADED:-} ]] && return 0). - 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" - Keep the library free of side effects: only function definitions and defaults, no
set -e, noexitat load time (callers own their strict mode). - Prefix library functions and locals (
opskit_init,_try) to avoid collisions and dynamic-scoping bugs. - Add bats tests for the library itself, and configure
.shellcheckrcwithsource-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.
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?BeginnerA 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.BeginnerYour team decides all scripts must pass ShellCheck. The first run reports 400 findings across 60 scripts. How do you roll this out?Intermediate