Published on Linux Journal (http://www.linuxjournal.com)
Automatically re-start script as root
By Mitch Frazier
Created 2008-04-17 17:12

If you use sudo you can automatically re-start scripts that need to be run as root by adding a check at the beginning of the script and executing sudo if the script is not running as root:

  if [[ $UID -ne 0 ]]; then
    sudo -p 'Restarting as root, password: ' bash $0 "$@"
    exit $?
  fi

The inclusion of "bash" in the sudo command is to avoid problems if the script does not have its execute bit set. The "exit $?" causes the shell to exit with the status from the script instance that sudo runs.

__________________________

Mitch Frazier is the System Administrator at Linux Journal.


Source URL: http://www.linuxjournal.com/content/automatically-re-start-script-root-0