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!
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
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.execis 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: