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
add comment

3 Answers

up vote 21 down vote accepted
#!/bin/bash
if [[ $EUID -ne 0 ]]; then
   echo "This script must be run as root" 
   exit 1
fi
share|improve this answer
2  
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. –  Bruce Connor 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
add comment
#!/bin/bash
[[ $(id -u) != 0 ]] 
echo $?
share|improve this answer
add comment
#!/bin/bash
uid=`id -u $USERNAME`
if [ "$uid" == "0" ]
then
    echo 1
else
    echo 0
fi
share|improve this answer
add comment

Your Answer

 
discard

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.