Bash script run by root or not

How do I check bash script is being run as a root user or not. when creating a new account a user ID is assigned to each user. Bash shell store value user ID is $UID and $EUID variable. Bash script the essential for DevOps Roles.

Example, To check bash script run by root or not.

Using $UID variable

#!/bin/bash
if [ "$(id -u)" != "0" ]; then
   echo "Please run by root user" 2>&1
   exit 1
else
   echo "Mounting...."
   mount /dev/sdb4 /mnt/disk4
fi

Using $EUID variable

#!/bin/bash
if [[ $EUID -ne 0 ]]; then
   echo "Please run by root user" 2>&1
   exit 1
else
   echo "Mounting...."
   mount /dev/sdb4 /mnt/disk4
fi

Conclusion

Thought the article, you can use Bash script run by root or not as above. I hope will this your helpful. More details refer to Bash script.

About HuuPV

My name is Huu. I love technology and especially Devops Skill such as Docker, vagrant, git so forth. I likes open-sources. so I created DevopsRoles.com site to share the knowledge that I have learned. My Job: IT system administrator. Hobbies: summoners war game, gossip.
View all posts by HuuPV →

Leave a Reply

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

This site uses Akismet to reduce spam. Learn how your comment data is processed.