Least-Privilege Execution and sudo Discipline
Drop privileges, scope sudo rules tightly, and validate effective UID before risky operations.
Why Least-Privilege Matters in Shell Scripts
Most security breaches in automation happen not because of exotic exploits, but because scripts run with more privileges than they need. A cron job running as root that only needs to rotate a log file is an accident waiting to happen.
The principle of least privilege states: every process should operate using only the permissions required to do its job — and no more. In Bash scripting this means:
- Running as an unprivileged user whenever possible
- Elevating to root only for the specific commands that require it
- Dropping privileges as soon as elevated work is done
- Never storing or inheriting credentials beyond their scope
This lesson walks through the concrete techniques: sudo scoping, su drops, UID validation guards, and sudoers hardening — building a disciplined privilege model for production scripts.
Checking Effective UID Before Risky Operations
Before any block of code that truly requires root, your script should verify it is running with the expected effective UID. Never assume; always assert.
$EUID is a Bash special variable holding the effective user ID of the current process. Root always has EUID 0. Checking it at the top of a script — or around a privileged block — prevents accidental execution under the wrong identity.
Use this guard pattern:
#!/usr/bin/env bash
set -euo pipefail
# Guard: this script must NOT run as root.
if [[ "$EUID" -eq 0 ]]; then
echo "ERROR: Do not run this script as root. Use a normal user account." >&2
exit 1
fi
echo "Running as UID $EUID — proceeding safely."All lessons in this course
- Preventing Command and Argument Injection
- Secure Secret Handling and Environment Hygiene
- Least-Privilege Execution and sudo Discipline
- Static Analysis and Auditing with ShellCheck