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

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 →

  1. 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
    
  2. Re-executing with runuser (or sudo -u deploy) keeps the operator experience simple while guaranteeing ownership.
  3. Set umask 027 so 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.

All Shell Scripting questions Roadmap: Shell scripting (Bash)

More on Scenarios: writing and hardening scripts