krypted.com

Tiny Deathstars of Foulness

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.

December 21st, 2015

Posted In: Mac OS X, Mac OS X Server, Mac Security, Mass Deployment, Unix

Tags: , , , , , , , ,

  • Jim

    While the USER envar is available as a quick-and-dirty method to do this check, it’s not inherently reliable because the envar isn’t read-only (checked bash and zsh on OS X 10.11.2). The user can (re)set or unset it to any value they choose. If said script is executed with sudo, the USER envar can be especially problematic if sudoers isn’t configured to ignore the calling user’s environment, or sudo isn’t executed with the -H flag.

    I recommend using either ‘whoami’ (although the man page says it’s been obsoleted) or ‘id -u -n’ which don’t use user-modifiable environment variables.