Check if a script is running as root user in Linux

Channel: Linux
Abstract: then echo "Please run this script as a non-root user" exit 1 fi123456#then echo "Please run this script as root user" exit 1fi Check if a shell script

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.

#!/usr/bin/env bash if [ "$EUID" -ne 0 ];then echo "Please run this script as root user" exit 1 fi123456#!/usr/bin/env bash if [ "$EUID" -ne 0 ];then    echo "Please run this script as root user"    exit 1fi

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.

#!/usr/bin/env bash if [ `whoami` != 'root' ];then echo "Please run this script as root user" exit 1 fi123456#!/usr/bin/env bash if [ `whoami` != 'root' ];then    echo "Please run this script as root user"    exit 1fi

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.

#!/usr/bin/env bash if [ "$EUID" -eq 0 ];then echo "Please run this script as a non-root user" exit 1 fi123456#!/usr/bin/env bash if [ "$EUID" -eq 0 ];then    echo "Please run this script as a non-root user"    exit 1fi

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.

Ref From: tecadmin

Related articles