Mac OS X,  Mac OS X Server,  Mac Security,  Mass Deployment,  Unix

Bash: Check That A Script Is Running As Root

Pretty much every script I’m working on these days must be run as root. Checking what user is running something is pretty straight forward, as there’s a built-in shell variable for $USER that contains the user running a script. To see this real quick, simply run the following:

echo $USER

You can then put this into your scripts. I’ve been using the same block of code for decades, which can be run in a script by itself if you’d like to paste this into one.

if [[ $USER != "root" ]]; then
echo "This script must be run as root"
else
echo "You are root"
exit 1
fi

Note: Keep in mind that the built-in $USER variable is case sensitive.

Obviously, most people won’t keep the lines that contain the else and you are root echo statements. You can just remove these or replace them with the meat of your script that requires elevated privileges to run. Enjoy.