Bash Scripting Tip: Running a script as root
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.
Nice coding style! But I have one shorter way. :)
Comment by Maurcio Teixeira (netmask) — 2/24/2006 @ 4:39 am
Maurcio,
Cool! - there are always shorter/better ways of doing things in bash! :) One nice thing about having this in a function like in my case, is that for complex scripts which use things such as
getopsand/or have usage information, etc, I don’t want people to have to type in roots password to get to the--help/-hinfo or any other options which do not require root privs. Also, having the the command line arguments saved saved and exported allows me to callchk_rootfrom whithin other sub-shells or functions and preserve the command line arguments to the top-level script. I should have mentioned that in the text above. Thanks for the input!Comment by marc — 2/24/2006 @ 6:54 am
The line
or
didn’t work on my system. When using more than one parameter, I get the error-message “Unknown id: param1″ from su
I have to use:
PS. Following code enables you to use more than 9 parameters (untested):
Comment by Benjamin Schmidt — 9/9/2007 @ 8:53 am