Request root privilege from within a script
I have a script which can run as sudo script.sh
or pkexec script.sh
It would be much nicer from the user point of view if the script asked for the password from the user when just running it by name script.sh
.
How can I "embed" request to pkexec
or sudo
to run the whole script with root privilege?
Note that running everything with sudo sh -c
might not be the best solution as I have functions in the script.
Solution 1:
This'll work:
echo "$(whoami)"
[ "$UID" -eq 0 ] || exec sudo "$0" "$@"
example:
./test.sh
blade
[sudo] password for blade:
root
Solution 2:
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