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.
You 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.
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.
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.
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.
If you appreciate what we share in this blog, you can support us by:
- Stay connected to: Facebook | Twitter | Google Plus | YouTube
- Subscribe email to recieve new posts from us: Sign up now.
- Start your own blog with SSD VPS - Free Let's Encrypt SSL ($2.5/month).
- Become a Supporter - Make a contribution via PayPal.
- Support us by purchasing Ribbon Lite Child theme being using on this website.
We are thankful for your support.