Check if Bash Script is ran by Root User


Read {count} times since 2020

Root users have the privilege to do administrative stuff in Linux and if you’re creating a Bash script to install something or change something in the system, you need root. So, checking whether the script was ran by root is very important.

if [ "$EUID" -ne 0 ]
   then echo "Please run as root"
   exit
fi

There is no else condition. You can add the code which will does stuff in root after the above. If root didn’t ran the script, then the script will terminate itself without continuing after “Please run as root” message is displayed.

Example :

if [ "$EUID" -ne 0 ]
   then echo "Please run as root"
   exit
fi
print "The script is continuing"

 

Show Comments