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

You want tests for existing scripts that call `curl`, `aws` and `systemctl`. How do you test them without touching real systems?

IntermediateScenarioScenarios: writing and hardening scripts
Answer

Situation read → External commands must be replaced with controllable fakes, and each test needs an isolated filesystem.

What I'd do →

  1. Use bats-core; put stub executables in tests/stubs/ and prepend that directory to PATH in setup().
  2. Each stub logs its arguments to a file and returns canned output or an exit code from an environment variable (STUB_CURL_RC=22).
  3. Make the script configurable through environment variables for paths (STATE_DIR, LOG_FILE, CONF), defaulting to production paths.
  4. Assert on exit status, output, files created and the stub call log.
  5. Run bats tests and shellcheck in CI on every PR.

Why → PATH stubs need no changes to the script's code and make failure paths (timeouts, 503s, AccessDenied) easy to test.

Interview tip → Point to a failure-path test, such as "upload fails, so the script exits 1 and raises an alert". That is where scripts usually break.

All Shell Scripting questions Roadmap: Shell scripting (Bash)

More on Scenarios: writing and hardening scripts