Request root privilege from within a script
This'll work:
echo "$(whoami)"
[ "$UID" -eq 0 ] || exec sudo "$0" "$@"
example:
./test.sh
blade
[sudo] password for blade:
root
If you'd like a pretty dialog, try something like this. I ripped this straight out of something else I wrote, so it's got extra stuff you might not need or want, but it shows the general idea:
brand="My Software"
# Check that the script is running as root. If not, then prompt for the sudo
# password and re-execute this script with sudo.
if [ "$(id -nu)" != "root" ]; then
sudo -k
pass=$(whiptail --backtitle "$brand Installer" --title "Authentication required" --passwordbox "Installing $brand requires administrative privilege. Please authenticate to begin the installation.\n\n[sudo] Password for user $USER:" 12 50 3>&2 2>&1 1>&3-)
exec sudo -S -p '' "$0" "$@" <<< "$pass"
exit 1
fi
This uses whiptail, which you can install if you don't already have it:
sudo apt-get install whiptail
blade19899's answer is indeed the way to go, however one could also call sudo bash
in the shebang:
#!/usr/bin/sudo bash
# ...
The obvious caveat is this will work only as long as the script is called with ./script
and will fail as soon as the script is called with bash script
.