Take the 2-minute tour ×
Ask Ubuntu is a question and answer site for Ubuntu users and developers. It's 100% free, no registration required.

I'm writing a simple bash script, but I need it to check whether it's being run as root or not. I know there's probably a very simple way to do that, but I have no idea how.

Just to be clear:
What's a simple way to write a script foo.sh, so that the command ./foo.sh outputs 0, and the command sudo ./foo.sh outputs 1?

share|improve this question

3 Answers 3

up vote 22 down vote accepted
if [[ $EUID -ne 0 ]]; then
   echo "This script must be run as root" 
   exit 1
share|improve this answer
I'm accepting this one cause (after some testing) using the system variable EUID turned out to be (approx 100 times) faster than running a command (id -u), but all of the answers worked great. –  Malabarba Dec 2 '10 at 11:59
Thanks aneeshep. I didn't even know there was an environment variable for the effective UID. –  Delan Azabani Dec 2 '10 at 12:31
[[ $(id -u) != 0 ]] 
echo $?
share|improve this answer
uid=`id -u $USERNAME`
if [ "$uid" == "0" ]
    echo 1
    echo 0
share|improve this answer

Your Answer


By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.