Notes

How to check if a user is root

Edit on GitHub

Bash Scripting

Check for the user identifier: $EUID. root is always 0.

1#!/bin/bash
2if [[ $EUID -ne 0 ]]; then
3   echo "This script must be run as root" 
4   exit 1
5fi

$EUID -ne 0 basically means if user is not root

The following script will use the whoami command to see what user you are. If you are root, it’ll continue running the script. If not, it’ll exist the script telling you that you are not root and need to use sudo.

1#!/bin/bash
2
3owner=$(who am i | awk '{print $1}')
4 
5if [ "$(whoami)" != 'root' ]; then
6  	echo "You don't have permission to run $0 as non-root user. Use sudo"
7	exit 1;
8fi