Check root user permissions in bash scripts

Posted by Dan Sosedoff on March 09, 2009

For example, in your bash shell script you`re going to use some root-specific commands like network operations, mounting devices and so on. There are couple easy ways to check if your script is executing under root privileges.

#!/bin/bash
# ...
if [ "$(id -u)" != "0" ]; then
   echo "This script must be run as root" 1>&2
   exit 1
fi
# ...

Another way: use EUID. When user account created a user ID is assigned to each user. Bash shell stores the user ID in $UID variable. Your effective user ID is stored in $EUID variable.

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