Bash Scripting: Require script to be run as root (or with sudo)

Solution 1:

To pull the effective uid use this command:

id -u

If the result is ‘0’ then the script is either running as root, or using sudo. You can run the check by doing something like:

if [[ $(/usr/bin/id -u) -ne 0 ]]; then
    echo "Not running as root"

Solution 2:

I assume you know that by changing the ownership to root

chown root:root file

and setting the permissions to 700

chmod 700 file

you will accomplish the same thing - without the suggestion to run as sudo.

But I will post this answer for completeness.

Solution 3:

The bash variable $EUID shows the effective UID the script is running at, if you want to make sure the script runs as root, check wether $EUID contains the value 0 or not:

if [ $EUID -ne 0 ]; then
    echo "$0 is not running as root. Try using sudo."
    exit 2

This is better than the solution with /usr/bin/id (for bash scripts!) because it doesn't require an external command.

Solution 4:

What is your objective here, to inform the user that they should run the script as root or as some kind of security precaution?

If you just want to inform the user than any of the uid suggestions are fine, but they're as useful as tyres on a horse as a security precaution - there's nothing to stop a user from copying the script, taking out the if statement, and running it anyway.

If this is a security issue then the script should be set to 700, owned by root:root, so that it is not readable or executable by any other user.

Solution 5:

You can use whoami command as well.

if [ ! "`whoami`" = "root" ]
    echo "\nPlease run script as root."
    exit 1