Check If a script is executed as root?

2

1

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 ?

The KingMaker

Posted 2013-11-15T16:06:52.200

Reputation: 103

Answers

7

#!/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

Hennes

Posted 2013-11-15T16:06:52.200

Reputation: 60 739

This doesn't work, produces: [[: not found – Adambean – 2015-06-14T12:51:20.860

2

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)

konqui

Posted 2013-11-15T16:06:52.200

Reputation: 504

+1 just for seeing root:wheel rather than root:root. ;-) – Hennes – 2013-11-15T17:40:17.550

What do you mean with just seeing root:wheel instead of root:root. – konqui – 2013-11-15T17:52:12.980

Lots of Linux distributions seems to default to root:root, while FreeBSD (and possible a few linuxes) use root:wheel. – Hennes – 2013-11-15T17:55:21.153

Ok now is clear misunderstood his question. The wheel came in by mistake cause a use more unix (bsd and mac than linux) – konqui – 2013-11-15T17:59:30.563