Check to see if a script was run as root
If you need to make sure a script is run as root, add the following to the start of the script:
if [[ $UID -ne 0 ]]; then
echo "$0 must be run as root"
exit 1
fi
Mitch Frazier is an Associate Editor for Linux Journal and the Web Editor for linuxjournal.com.










This week 5 lucky Members will receive a copy of The Official Ubuntu Server Book by Benjamin Mako Hill and Linux Journal's very own Kyle Rankin. No entry necessary. Check back here early next week to find out who the lucky Online Members are.




Comments
I don't belive this is the
I don't belive this is the right way of checking the user. This is as easy as your solution but is harder to bypass.
to bypass your code:
$ sh
$ export UID=0
run command
better way:
LUID=$(id -u)
if [[ $LUID -ne 0 ]]; then
echo "$0 must be run as root"
exit 1
fi
hope this help
bye
Not a problem, at least with bash
Bash won't let you do "export UID=0", UID is a read-only variable.
Mitch Frazier is an Associate Editor for Linux Journal and the Web Editor for linuxjournal.com.
Effective User ID
You may find it more useful to check for the Effective User ID (EUID) rather than the plain User ID (UID). Then your script will work with SUID cases.
Just replace $UID with $EUID in the above snippet.
Maybe
As I recall the set-uid bit doesn't work on shell scripts, so unless your script is going to be run by a compiled program that has the set-uid bit set this wouldn't make any difference. Or am I missing something here?
Mitch Frazier is an Associate Editor for Linux Journal and the Web Editor for linuxjournal.com.
bash != sh
$ sudo sh -c 'set' | grep UID
SUDO_UID='1000'
$ sudo bash -c 'set' | grep UID
EUID=0
SUDO_UID=1000
UID=0
bash provides the environment variable 'UID', but other shells do not. Additionally '[[', while not bash specific is not present in all shells. A better solution (albeit, one dependent on 'id'):
uid=`id -u` && [ "$uid" = "0" ] ||
{ echo "must be root"; exit 1; }
Whose id command?
A little safer/more reliable to do:
uid=$(/usr/bin/id -u) && [ "$uid" = "0" ] ||
{ echo "must be root"; exit 1; }
Use #!/bin/bash
I always put "#!/bin/bash" at the top of my scripts, but beyond that I don't worry about non-bash environments. However, there certainly are some scripts that may run or need to run in an environment where bash does not exist.
Mitch Frazier is an Associate Editor for Linux Journal and the Web Editor for linuxjournal.com.
Post new comment