Check if bash script is run with root permissions

Short code snippet to check if bash script is run with root permissions.

Check if bash script is run with root permissions example code.

Below I present code that verifies if bash script is ran with root permissions. The code works without any problems with sudo.

 

Check if bash script is run with root permissions example

#!/bin/bash

# Check if ran with root permissions
if [ `id -u` -ne 0 ]; then
   printf "The script must be run as root! (you can use sudo)\n"
   exit 1
fi

Explanation

The script uses id utility that displays real and effective user ID. Thanks to this utility, we can verify that user runs the script with root privileges. This technique makes the script to effectively detect use of sudo as well.

The root ID is 0 (zero), therefore we compare ID returned by id utility with number zero. If the match is made, we know that the script is executed with root permissions. If it’s not, then we know that the user has no root permissions. In this case, we display an information message and leave the script.