Take the 2-minute tour ×
Super User is a question and answer site for computer enthusiasts and power users. It's 100% free, no registration required.

I have a script that requires root privileges. I have to execute it either via sudo or from an account with uid 0 (e.g. root).

If the script is not executed with sufficient rights then I want that script to echo "Run as Root" and exit 1.

How can I achieve this ?

share|improve this question
add comment

2 Answers 2

up vote 5 down vote accepted
#!/usr/bin/env bash
if [[ $EUID -ne 0 ]]; then
   echo "This script must be run as root" 
   exit 1
fi

// Rest of the script here

Source.

EUID is the effecvtive UID the script is running as.

[[ ne ]] is a test on not equal.

0 is the uid of root (or rather, the uid you want. The name root is the most often name but that can be changed and there can be multiple accounts with uid 0

share|improve this answer
add comment

You could also make the script just executable by root.

chmod 700 script (just the file owner can run the script)

chown root:wheel script (set file owner to root)

share|improve this answer
    
+1 just for seeing root:wheel rather than root:root. ;-) –  Hennes Nov 15 '13 at 17:40
    
What do you mean with just seeing root:wheel instead of root:root. –  konqui Nov 15 '13 at 17:52
    
Lots of Linux distributions seems to default to root:root, while FreeBSD (and possible a few linuxes) use root:wheel. –  Hennes Nov 15 '13 at 17:55
    
Ok now is clear misunderstood his question. The wheel came in by mistake cause a use more unix (bsd and mac than linux) –  konqui Nov 15 '13 at 17:59
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.