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

A 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.

BeginnerScenarioScenarios: writing and hardening scripts
Answer

Situation read → The script assumes a terminal. Under cron, stdin and stdout are not TTYs.

What I'd do →

  1. Enable colours only when stdout is a terminal and NO_COLOR is unset:
    if [[ -t 1 && -z ${NO_COLOR:-} ]]; then RED=$'\e[31m' RST=$'\e[0m'; else RED='' RST=''; fi
    
  2. Never prompt without a terminal: [[ -t 0 ]] || die "refusing to prompt without a TTY; pass --yes".
  3. Pass non-interactive flags to tools: apt-get -y, DEBIAN_FRONTEND=noninteractive, ssh -o BatchMode=yes, kubectl --context explicitly.
  4. Redirect stdin from /dev/null in the cron line to be safe: ... < /dev/null.

Why → Interactive assumptions are the main reason scripts hang in automation.

Interview tip → Name ssh -o BatchMode=yes, which makes SSH fail instead of waiting for a password.

All Shell Scripting questions Roadmap: Shell scripting (Bash)

More on Scenarios: writing and hardening scripts