Question

How to Check if Running as root in a BASH Script?

Posted December 23, 2019 1.3k views
Linux BasicsLinux Commands

I’m working on a BASH script but I do not want to allow people to run the script as root for security measures. Does anyone know what’s the best way to stop the execution of the script if it is ran as root?

These answers are provided by our Community. If you find them useful, show some love by clicking the heart. If you run into issues leave a comment, or add your own answer to help others.

×
3 answers

Hello,

There are a few ways to check that. But how I usually do that is to check if the $EUID matches 0. So the script would look something like this:

#!/bin/bash

if (( $EUID == 0 )); then
    echo "Please do not run as root"
    exit
fi

If you put this on top of your script it would exit in case that the EUID is 0 and would not execute the rest of the script.

Hope that this helps!
Regards,
Bobby

Hi @ServerEnthusiast,

As @bobbyiliev said, there are a few ways to check that so here is my way.

What I find best when I’m writing in any language is to place variables whenever possible. If you are going to reuse the command, it’s better to have it in a variable.

Here is how I’ll usually do it, it’s more or less the same as above however with a bit of difference

#!/bin/bash

#Check if the script is ran by root
SYSTEM_USER_NAME=$(id -un)
if [[ "${SYSTEM_USER_NAME}" == 'root'  ]]
then
    echo 'You are running the script as root'
    exit 1
fi

I would like to point out, both mine and @bobbyiliev suggestion’s would work. It’s really up to you which you decide to choose. What you need to do is to stay consistent. If you use one way, stay consistent and use it through the script/application you are building. It’s gonna be easier for you to read later. :)

Regards,
KDSys

Hello, @ServerEnthusiast

The examples provided by @bobbyiliev and @KDSys should help you to check if the script is executed from the root username.

Something to keep in mind is not to use the whoami command in order to check if the script is executed from root. A root user does not have to be named “root”. whoami returns the first username with user ID 0. $USER contains the name of the logged in user, which can have user ID 0, but have a different name.

As per @KDSys example, you can use: id -un in order to be sure that the script is actually executed from the root username.

This is from the man page if id

-u, --user
print only the effective user ID
-n, --name
print a name instead of a number, for -ugG

Regards,
Alex

Submit an Answer