Bash Scripting: Require script to be run as root (or with sudo)

bashpermissionsrootscripting

I'm trying to write a bash script (in Ubuntu) that will backup a directory using tar.

How can I do a check in the script so that it can only be run as root (or with sudo)?

For instance, if a user runs the script, it should say that this script must be run with sudo privileges, and then quit. If the script is executed as root, it will continue past the check.

I know there has to be an easy solution, I just haven't been able to find it by googling.

Best Answer

To pull the effective uid use this command:

id -u

If the result is ‘0’ then the script is either running as root, or using sudo. You can run the check by doing something like:

if [[ $(/usr/bin/id -u) -ne 0 ]]; then
    echo "Not running as root"
    exit
fi