When scripting admin type tools in bash, many times you need to run a script as root. A script sometimes requires mounting file systems, adding users, moving/editing/renaming files and some other things that the user executing the script may not have rights to do.
In my case, I have written some bash scripts to help some engineers on my team at work do some things that require root access on their machines. These scripts are all available on an NFS exported directory. I don’t want to set up sudo entries on the engineer’s machines for the multiple and constantly changing scripts in this directory so adding functionality that will ensure these scripts run as root makes it possible to place scripts in the directory and let them use them without intervention on my part (they all have root access on their own machines).
Here’s a simple bash scripting tip – a function – that will prompt a user for the root password if they are not root, and re-runs the current script as root, preserving the command line arguments.
CMDLN_ARGS="$@" # Command line arguments for this script
export CMDLN_ARGS
# Run this script as root if not already.
chk_root () {
if [ ! $( id -u ) -eq 0 ]; then
echo "Please enter root's password."
exec su -c "${0} ${CMDLN_ARGS}" # Call this prog as root
exit ${?} # sice we're 'execing' above, we wont reach this exit
# unless something goes wrong.
fi
}
# Call this function early on - now or before your script's main loop starts.
chk_root
The exec call replaces the current process with the one that is being called – in this case, the same script.
Happy scripting.
Comments
Leave a comment Trackback