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 ?

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

// Rest of the script here


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

  • This doesn't work, produces: [[: not found – Adambean Jun 14 '15 at 12:51

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)

  • +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

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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