Bash Tips: Automatically Go Root

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!

2 Comments

  1. GX says:

    Thanks for the tip I been looking for this for a while.. one question.. will this work with arguments or must I pas them again?, if so is the a more elegant (or correct) way than:

    exec su -c "sh $0 $1 $2 $3 ..."

    also just befor fi (if ends) shouldnt you exit to avoid continuing?

    GX

  2. You’re right. The line should have “$@” appended:

    exec sudo sh $0 "$@"

    $@ in quotes will get all the arguments as they were passed to the original script.

    exec is a nice command that replaces the currently executing script with the new script. You don’t have to exit after the exec, it’s implied. Try this in a script:

    #!/bin/sh
    echo first
    exec true
    echo last       # you'll never see this line
    

Leave a Comment

HTML: You can use these tags: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>