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"
- Store complex regexes in variables and keep them unquoted on the right of
=~. - Normalize first if needed (
env=${env,,}). - 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.
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?BeginnerTen scripts in a repo each copy-paste their own `log`, `die`, retry and config loading. How do you fix this?IntermediateA 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.Beginner