How to check if running as root in a bash script

Share this post to your friends !

WriteBash - 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.

whoami

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-01 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-02 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
else
    echo "You are normal user"
    // Do command if user not is root
fi

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.

Conclusion

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.

If you liked this article, then please subscribe to our YouTube Channel for more video tutorials. You can also find us on Twitter and Facebook.


Share this post to your friends !
If you appreciate what we share in this blog, you can support us by:
  1. Stay connected to: Facebook | Twitter | Google Plus | YouTube
  2. Subscribe email to recieve new posts from us: Sign up now.
  3. Start your own blog with SSD VPS - Free Let's Encrypt SSL ($2.5/month).
  4. Become a Supporter - Make a contribution via PayPal.
  5. Support us by purchasing Ribbon Lite Child theme being using on this website.

We are thankful for your support.

single post bottom banner
«« »»

Got something to say? Join the discussion

Please keep in mind that all comments are subject to our Comment Policy. Your email address will not be published.
This site uses Akismet to reduce spam. Learn how your comment data is processed.