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