I\'m writing a script that requires root level permissions, and I want to make it so that if the script is not run as root, it simply echoes \"Please run as root.\" and exit
A few answers have been given, but it appears that the best method is to use is:
id -u
This appears to be more reliable than the other methods, and it seems that it return an id of 0 even if the script is run through sudo
.
There is a simple check for a user being root.
The [[ stuff ]]
syntax is the standard way of running a check in bash.
error() {
printf '\E[31m'; echo "$@"; printf '\E[0m'
}
if [[ $EUID -eq 0 ]]; then
error "Do not run this as the root user"
exit 1
fi
This also assumes that you want to exit with a 1 if you fail. The error
function is some flair that sets output text to red (not needed, but pretty classy if you ask me).
If the script really requires root access then its file permissions should reflect that. Having a root script executable by non-root users would be a red flag. I encourage you not to control access with an if
check.
chown root:root script.sh
chmod u=rwx,go=r script.sh
id -u
is much better than whoami
, since some systems like android may not provide the word root.
Example:
# whoami
whoami
whoami: unknown uid 0
#!/bin/bash
# GNU bash, version 4.3.46
# Determine if the user executing this script is the root user or not
# Display the UID
echo "Your UID is ${UID}"
if [ "${UID}" -eq 0 ]
then
echo "You are root"
else
echo "You are not root user"
fi
Editor's note: If you don't need double brackets, use single ones for code portability.