Shell – How to retroactively make a script run as root

rootshell-scriptsudo

I'm writing a shell script, that needs to be run with root privileges.

I can check if a user has root privileges with sudo -nv || echo "no sudo", but that doesn't help me, if his credentials are still cached by sudo, but he didn't call my script with it. So I have no way of reacting to a user, not calling my script with sudo.

I could put sudo in front of every command that needs it, so just checking to see if the user has root privileges would be enough, but it seems to me, that there should be a better solution.

I'm looking for a command, that I can put into my script, that asks the user for root privileges and, if provided, executes the rest of the script, as if the user called it with root privileges in the first place.

What I want:

#!/bin/bash

if ! command; then        # what I'm looking for
    echo "This script needs root privileges."
    exit 1
fi

mv /bin/cmd1 /bin/cmd2    # requires root

Edited 2 times

Best Answer

Test if you are root, and if not, restart with sudo, for example:

#! /bin/bash

if [[ $EUID -ne 0 ]];
then
    exec sudo /bin/bash "$0" "$@"
fi
Related Question