Require sudo in bash script

Use the following code snippet in bash scripts that require root privileges to prompt the user to become root using sudo.

if [ "$EUID" -ne 0 ]; then
    echo "This script requires root."
    sudo su -s "$0"
    exit
fi

Info

If you need to pass arguments to the script, you will need to tweak the sudo line a little bit such as:

sudo su -s "$0" root $1 $2