I run a collection of Bash scripts periodically for system maintenance and in relation to this website. Of those, there are two or three that have to run with root privileges. That’s no problem, a simple sudo
is all that’s required to elevate the privileges of a script at run time.
The problem is that I forget. I run these scripts in the normal manner then bang my head against a wall trying to figure out why they don’t perform as they should.
To this end, I’ve put together the following little header for these scripts. The header simply checks whether or not the script is running as root. If it is, all’s well and good. If it isn’t, then the header forces the script to re-run itself with a sudo
prefix (so it will ask for the root password before continuing).
#!/bin/sh
if [ "$(whoami)" != 'root' ]; then
echo 'This script must run as "root".'
echo 'Enter password to elevate privileges:'
SCRIPTPATH=$( cd $(dirname $0) ; pwd -P )
SELF=`basename $0`
sudo $SCRIPTPATH'/'$SELF
exit 1
fi
clear
echo 'Script running with root privileges.'
# Your code here
This should spare me some headaches!