Stop a script from running if it’s not root

This is a very short post and relies on the knowledge that UID of root user is always 0 regardless of the name of the root account. If the effective UID returned by id -u is not zero, the user is not executing the script with root privileges. Below simple code can be used to check against if script is running as root or not:

#!/bin/sh

if [ "$(id -u)" -ne 0 ]; then
        echo 'This script must be run by root user' > &2
        exit 1
fi

 

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s