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 →
- Enable colours only when stdout is a terminal and
NO_COLORis unset:if [[ -t 1 && -z ${NO_COLOR:-} ]]; then RED=$'\e[31m' RST=$'\e[0m'; else RED='' RST=''; fi - Never prompt without a terminal:
[[ -t 0 ]] || die "refusing to prompt without a TTY; pass --yes". - Pass non-interactive flags to tools:
apt-get -y,DEBIAN_FRONTEND=noninteractive,ssh -o BatchMode=yes,kubectl --contextexplicitly. - Redirect stdin from
/dev/nullin 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.
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?IntermediateYour team decides all scripts must pass ShellCheck. The first run reports 400 findings across 60 scripts. How do you roll this out?Intermediate