Prompt user to login as root when running a shell script

This is very easy to accomplish:

#!/bin/sh
[ "$(whoami)" != "root" ] && exec sudo -- "$0" "$@"

When the current user isn't root, re-exec the script through sudo.

Note that I am using sudo here instead of su. This is because it allows you to preserve arguments. If you use su, your command would have to be su -c "$0 $@" which would mangle your arguments if they have spaces or special shell characters.

If your shell is bash, you can avoid the external call to whoami:

(( EUID != 0 )) && exec sudo -- "$0" "$@"

You can check the UID as well:

 if [ $(id -u) != 0 ]; then
     echo "You're not root"
     # elevate script privileges
 fi

You can call the script itself and check:

#! /bin/bash

if [ "root" != "$USER" ]; then
  su -c "$0" root
  exit
fi

...