Bash Tips: Automatically Go Root

by
Annika Backstrom
in misc, on 28 June 2003. It is tagged #Computers and #Scripting.

I did some scripting for work yesterday, and came up with this little snippet to ensure important scripts will run as root:

#!/bin/sh

# check current user
WHO=`whoami`

# make sure we're superuser
if [ $WHO != root ]; then
    echo "Superuser privileges required, trying sudo."
    exec sudo sh $0 "$@"
fi

echo "I'm the superuser."

whoami is necessary because \$USER still holds the regular username even if sudo is in effect. exec replaces the current process with the new process, so no code after that line is executed.

There is a disadvantage to this method: If you've sudo'd recently, you (or anyone else that happens across your terminal) won't be prompted for a password. Change sudo sh $0 to su -c $0 for some added security. (Though you may have to invoke your program differently, ie. with the path given if it's not already in your $PATH.)

Update: added $@ to exec line. Thanks, GX!