Skip to content

Check if a script is running as root user in Linux

Category
Linux
On this page

Sometimes the shell scripts are required to run as the root user to perform some tasks with administrator privileges. Generally, that tasks can be achieved with the Sudo commands. If in some cases you still need to force the user to run the script as the root user, you can add code to your script to check if the script is running with the root user or not.

Check if a shell script running as root user

Add the following code at beginning of the shell script to check if the script is running as the root user. If the script is executed as a non-root account, it will exit with status code 1.

Here the EUID is the system variable that stored the user id (UID) of the currently logged-in user. The “root” user’s UID is always 0 on the Linux systems.

Instead of using the UID, you can also match the logged-in user name. The whoami command provides the currently logged user name. The below script will check if the script is running as a root user or not.

Check if a shell script running as non-root user

Sometimes the scripts are required to run as a non-root account. In that case, you can add the following snippet to check for a user account and continue only if the script is running as a normal user.

Conclusion

In this quick how-to guide, you have learned about adding restrictions in a shell script to run as a root user or non-root user. If it is running a different user, the script will exit immediately.

Rahul

Rahul Kumar is the founder and chief editor of TecAdmin.net. A Red Hat Certified Engineer (RHCE), he has worked in IT since 2009, with hands-on experience in Linux system administration, DevOps, web hosting, cloud platforms and automation. He started TecAdmin in 2013 to share practical, step-by-step guides, and leads its editorial work with one aim: making technical learning clear and useful for sysadmins, developers and beginners alike.

Leave a Reply

Your email address will not be published. Required fields are marked *


Back to top