Using BASH to find out if it’s running as root

 

Using Linux can be a fairly straight forward task for most users. But if you are not careful, you can do something that might be irreversible, like delete pictures of you trip to your mother-in-law’s house last summer. But for more important files like system files needed for basic operations, there is obviously a need to ensure that most users don’t do anything stupid by accident. Thus, certain operations are naturally prohibited for most users without special access. This is where root comes in.

When writing automated scripts with languages like BASH, there sometimes needs to be a way to find out if the script is running as root, especially if the script is doing potentially sensitive operations like dealing with core system files. However, as with anything Linux-related, there’s more than one way to peel an Apple, so I know there are probably other ways of finding out that go beyond the scope of this article.

The first method involves checking to see if the variable EUID (what’s called the Effective User ID) is equal to 0. When it’s running in normal mode, it typically shows a number like 1000, so a simple compare can be an easy way to detect if a script is running as root or not.

if [ "$EUID" -eq 0 ]
then
    printf "* WARNING: You are the root user. Be Careful!\n"
else
     printf "You are a normal user.\n"
fi

The second method involves checking the output of the whoami command and determining if the current user is set as root by comparing string values.

if [ 'whoami' == 'root' ]
then
    printf "* WARNING: You are the root user. Be Careful!\n"
else
    printf "You are a normal user.\n"
fi

DISCLAIMER: While I make a lot of effort to make sure the content I provide is high quality, that doesn’t mean that it will always work. If you find a problem in any of my posts, please let me know right away, and I will fix it to the best of my ability. Also, please be nice. We’re all mature individuals here, and we’re all still learning, even if we’re not currently in the classroom.

Comments