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.
More on Bash scripting tasks
Write the safe header you start every Bash script with, and explain each part.BeginnerWrite a script that alerts when any filesystem is above 80% usage.BeginnerParse an Nginx access log and print the top 10 client IPs by request count.BeginnerWrite a backup script that tars a directory with a timestamp and keeps only the last 7 backups.IntermediateWrite a health-check loop that polls a URL until it returns 200, with a timeout.IntermediateParse command-line flags `-e <env>`, `-v` (verbose) and `-h` in a Bash script.Intermediate