Check if user is root/sudo before running a script

Sometimes a script may need to only be run as root or using sudo, or run ensuring that it is not being run by root or using sudo. This quick post shows how to check if it’s the root user and exit the script.

File Permissions

The best way to make it that the script can only be run by root is to change ownership of the file to the root user and make it so only root can execute it. To change "myscript" to only run as root using filesystem permissions do this:

chown root myscript
chmod 0744 myscript

The above commands need to be run as the root user or using sudo. The chmod command makes it so all other users can still read the script but not execute it. To make it so they cannot read it either then do this:

chmod 0700 myscript

In the script

Sometimes you may want to move the checking into the shell script itself. This is also possible. Add the following to the start of the script to only allow root or sudo access:

if [ `whoami` != root ]; then
    echo Please run this script as root or using sudo

To make it so only non-root users should run the script do this:

if [ `whoami` = root ]; then
    echo Please do not run this script as root or using sudo