Bash: Check if you are root

Valic —  October 20, 2011 — 1 Comment

Using the following you can check if you are root or not when you run bash scripts.

Exmaple 1:

if [ $(whoami) != 'root' ]; then
echo "Must be root to run $0"
exit 1;

Example 2:

ROOT_UID=0 # Only users with $UID 0 have root privileges.
E_NOTROOT=87 # Non-root exit error.

if [ "$UID" -ne "$ROOT_UID" ]
echo "Must be root to run this script!"
echo "You are root!"

You can also use this in your bash scripts.


Posts Twitter Facebook

Editor in Chief at Debian-Tutorials, Linux enthusiast.

One response to Bash: Check if you are root

  1. hello

    example #2 is usually more portable so it’s a better idea to use this one.

    One example where #1 wouldn’t port very well, is on FreeBSD systems where by default you have two root users (with uid 0). One named ‘root’ and one named ‘toor’.

Leave a Reply