A 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?
BeginnerScenarioScenarios: writing and hardening scripts
Answer
Situation read → Running as root creates root-owned files the app cannot later modify, a classic source of Permission denied after a manual run.
What I'd do →
- Check the effective user at the top:
if [[ $(id -un) != deploy ]]; then if [[ $EUID -eq 0 ]]; then exec runuser -u deploy -- "$0" "$@"; fi echo "run as deploy: sudo -u deploy $0" >&2; exit 1 fi - Re-executing with
runuser(orsudo -u deploy) keeps the operator experience simple while guaranteeing ownership. - Set
umask 027so new files are not world-readable.
Why → Re-exec as the right user prevents the mistake instead of just reporting it.
Interview tip → Use $EUID (effective UID) rather than $USER, which is just an environment variable and can be wrong under sudo.
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?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.BeginnerYour team decides all scripts must pass ShellCheck. The first run reports 400 findings across 60 scripts. How do you roll this out?Intermediate