How to check if running as root in a bash script

by Daniel Pham
Published: Updated:

How to check if running root in a script bash? In most cases, bash script files are run by the root user in the system. Because these are system administrators, these scripts will need permission to install, change the system. But how can we check that the user is running as root when we execute a bash script?

Displays current user

To display the current user, in Linux you can use the commands below.


You see the result in the image below, we have two users: a normal user named writebash, an admin user is root.

How to check if running as root in a bash script
Display current user in Linux with ‘whoami’ command.

The second command you can use.

echo $EUID

What is EUID? from the man page:

EUID Expands to the effective user ID of the current user, initialized at shell startup. This variable is readonly.

How to check if running as root in a bash script
Display current user in Linux with ‘echo $EUID’ command.

You can see that the root user has an EUID value of 0.

Check if running as root in a bash script

The following script checks if the current user is root when running the script. You can copy it into your script and use it.

if (( $EUID == 0 )); then
    echo "You are root"
    // Do commands if user is root
    echo "You are normal user"
    // Do command if user not is root

Why do we use EUID command? Because, the root user is a common convention. However, there is no guarantee that the user name can not be changed.


Normally, we usually run the script with the root user. But in some cases, we need to test the user during execute the bash script, which ensures that the script does not crash when executed.

(This is an article from my old blog that has been inactive for a long time, I don’t want to throw it away so I will keep it and hope it helps someone).

0 0 votes
Article Rating

You may also like

Notify of
Inline Feedbacks
View all comments

DevOps Lite is a personal blog specializing in technology with main topics about DevOps, DevSecOps, SRE and System Administrator. Articles are shared for free and contributed to the community.



Subscribe my Newsletter for new blog posts. Stay updated from your inbox!

© 2021-2024 – All rights reserved.

Please write sources “” when using articles from this website.

This website uses cookies to improve your experience. We'll assume you're ok with this, but you can opt-out if you wish. Accept Read More

Would love your thoughts, please comment.x

Adblock Detected

Please support us by disabling your AdBlocker extension from your browsers for our website.