Bash

Detect Whether Running as Root

admin by @admin ADMIN
1h ago
May 31, 2026
Public
0 0 up · 0 down Sign in to vote
Several scripts must run as root (or refuse to). EUID is more reliable than `whoami == root` because sudo without -E may change one but not the other.
Bash
Raw
# Bail if not root
if [[ $EUID -ne 0 ]]; then
    echo "This script must be run as root (or via sudo)." >&2
    exit 1
fi

# Alternative: auto re-exec with sudo
if [[ $EUID -ne 0 ]]; then
    exec sudo -E "$0" "$@"
fi

# Bail if IS root (some scripts shouldn't run as root)
if [[ $EUID -eq 0 ]]; then
    echo "Don't run this as root." >&2
    exit 1
fi

# Reusable
is_root() { [[ $EUID -eq 0 ]]; }
need_root() { is_root || { echo "Need root" >&2; exit 1; }; }

need_root
apt update && apt upgrade -y
Tags

Save your own code snippets

Create a free account and build your private vault. Share publicly whenever you want.