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

A script accepts an environment name, a semantic version and a hostname from users. How do you validate them?

BeginnerScenarioScenarios: writing and hardening scripts
Answer

Situation read → Validate against an allow-list before the values touch any command.

What I'd do →

[[ $env =~ ^(dev|staging|prod)$ ]]                         || die "invalid env: $env"
[[ $version =~ ^v?[0-9]+\.[0-9]+\.[0-9]+(-[0-9A-Za-z.-]+)?$ ]] || die "invalid version: $version"
[[ $host =~ ^[a-z0-9]([a-z0-9-]{0,61}[a-z0-9])?(\.[a-z0-9]([a-z0-9-]{0,61}[a-z0-9])?)*$ ]] || die "invalid host: $host"
  1. Store complex regexes in variables and keep them unquoted on the right of =~.
  2. Normalize first if needed (env=${env,,}).
  3. Exit with code 2 for invalid input so callers can distinguish usage errors.

Why → Allow-lists block typos and injection in one step; deny-lists always miss a character.

Interview tip → Mention that validation must happen before the value is used in a path, ssh, sed or SQL.

All Shell Scripting questions Roadmap: Shell scripting (Bash)

More on Scenarios: writing and hardening scripts