Check whether a script is run as root and exit with a clear message if not.

BeginnerHands-onBash scripting tasks
Answer
if [[ $EUID -ne 0 ]]; then
  echo "This script must be run as root (try: sudo $0)" >&2
  exit 1
fi

Key trick → $EUID is the effective UID, so it is correct under sudo. $USER can be inherited and lie.

All Real-World Interview questions Roadmap: Interview readiness

More on Bash scripting tasks