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

The same script must run on engineers' macOS laptops and on Linux CI runners. What breaks, and how do you handle it?

IntermediateScenarioScenarios: writing and hardening scripts
Answer

Situation read → macOS ships Bash 3.2 and BSD userland; Linux has Bash 5 and GNU tools. Flags differ for sed -i, date -d, readlink -f, stat -c, grep -P, xargs -r.

What I'd do →

  1. Require Bash 4+ explicitly and tell macOS users to brew install bash coreutils gnu-sed grep:
    (( BASH_VERSINFO[0] >= 4 )) || { echo "need Bash 4+ (brew install bash)" >&2; exit 1; }
    
  2. Prefer portable forms: sed -i.bak ... && rm *.bak, $(cd "$(dirname "$0")" && pwd) instead of readlink -f.
  3. Where GNU behaviour is needed, detect and use gdate, gsed when present.
  4. Run CI on both ubuntu-latest and macos-latest if laptops are a supported target.
  5. Or remove the problem: run the script inside a container image with pinned tools.

Why → "Works on my Mac" is the shell equivalent of "works on my machine".

Interview tip → Mention that #!/usr/bin/env bash picks up Homebrew's Bash on macOS, while #!/bin/bash pins Apple's 3.2.

All Shell Scripting questions Roadmap: Shell scripting (Bash)

More on Scenarios: writing and hardening scripts