Bash – Allow Script to Run as Root Without Sudo

bashrootshell-scriptsudo

I'm new here and new to bash/linux.

My teacher gave me an assignment to allow a script to be run only when you're "really" root and not when you're using sudo. After two hours of searching and trying I'm beginning to think he's trolling me. Allowing only root is easy, but how do I exclude users that run it with sudo?

This is what I have:

if [[ $EUID -ne 0 ]]; then
  echo "You must be root to run this script."
  exit
fi

Best Answer

The only way I could think of is to check one of the SUDO_* environment variables set by sudo:

#!/usr/bin/env sh

if [ "$(id -u)" -eq 0 ]
then
    if [ -n "$SUDO_USER" ]
    then
        printf "This script has to run as root (not sudo)\n" >&2
        exit 1
    fi
    printf "OK, script run as root (not sudo)\n"
else
    printf "This script has to run as root\n" >&2
    exit 1
fi

Notice that of course this solution is not future proof as you cannot stop anyone from setting a variable before running the script:

$ su
Password:
# SUDO_USER=whatever ./root.sh
This script has to run as root (not sudo)
# ./root.sh
OK, script run as root (not sudo)
Related Question