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?
This textbox defaults to using Markdown to format your answer.
You can type !ref in this text area to quickly search our full set of tutorials, documentation & marketplace offerings and insert the link!
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.
Sign up for Infrastructure as a Newsletter.
Working on improving health and education, reducing inequality, and spurring economic growth? We'd like to help.
Get paid to write technical tutorials and select a tech-focused charity to receive a matching donation.
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:
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
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
Regards, Alex
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
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