Table of Contents
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.
whoamiYou see the result in the image below, we have two users: a normal user named writebash, an admin user is root.

The second command you can use.
echo $EUIDWhat 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.

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
fiWhy 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.
(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).