Detect whether current user is root in Bash
TL; DR
[[ `id -u` -ne 0 ]] && echo "Not root" || echo "Is root"
Introduction
When working with Bash scripts, there are times when you want to check whether the current user is the root user. This is especially important when running certain commands that require root privileges. In this blog post, we will discuss how to detect whether the current user is root in Bash.
Checking the User ID
The easiest way to check whether the current user is root is to check the user ID (UID). In Linux, the root user has a UID of 0. Therefore, we can check the UID of the current user using the following command:
if [ $(id -u) -eq 0 ]; then
echo "User is root"
else
echo "User is not root"
fi
This command uses the id
command to get the UID of the current user and compares it to 0 using the -eq
operator. If the UID is 0, then the user is root and the script will output “User is root”. If the UID is not 0, then the user is not root and the script will output “User is not root”.
Checking the User Name
Another way to check whether the current user is root is to check the user name. In Linux, the root user has a user name of “root”. Therefore, we can check the user name of the current user using the following command:
if [ $(whoami) = "root" ]; then
echo "User is root"
else
echo "User is not root"
fi
This command uses the whoami
command to get the user name of the current user and compares it to “root” using the =
operator. If the user name is “root”, then the user is root and the script will output “User is root”. If the user name is not “root”, then the user is not root and the script will output “User is not root”.
Leave a message
Disclaimer
- Welcome to visit the knowledge base of SRE and DevOps!
- License under CC BY-NC 4.0
- Made with Material for MkDocs and improve writing by generative AI tools
- Copyright issue feedback me#imzye.com, replace # with @