You are not logged in.

#1 2008-03-07 05:30:15

B-Con
Member
From: USA
Registered: 2007-12-17
Posts: 554
Website

Tell if executing as root

I have a Bash script that requires root privileges to its work. I want to bail out of the script if it's not being run as root, lest it try and fail a couple dozen commands. I could just make the script only executable by root, but it got me to wondering if there's any elegant/reliable way for a script to check with what permissions it's being run?

Offline

#2 2008-03-07 05:37:07

brebs
Member
Registered: 2007-04-03
Posts: 3,742

Re: Tell if executing as root

[[ "${EUID}" = "0" ]] && ( echo "Do not run as root." ; exit 1 )

Offline

#3 2008-03-07 06:26:47

jbromley
Member
From: Pasadena, CA
Registered: 2007-02-04
Posts: 268

Re: Tell if executing as root

I would try using the id command. It tends to exist on every system and root tends to nearly always have uid 0. So you could do something like:

if [[ $(id -u) -ne 0 ]]; then
    echo "This script must be run as root."
    exit
fi

This will work in bash. You may have to make some adjustments if you are using another shell, but still id -u is probably the right start.

Regards,
j

Offline

#4 2008-03-19 06:57:32

B-Con
Member
From: USA
Registered: 2007-12-17
Posts: 554
Website

Re: Tell if executing as root

A belated thanks, guys.

A question on permissions, why is it that the following happens (my user is UID = 1000):

b-con@beacon:~$ sudo id -u
0

b-con@beacon:~$ sudo echo `id -u`
1000

Why does echo seem change which user is executing the command?

Offline

#5 2008-03-19 08:18:06

awagner
Member
From: Mainz, Germany
Registered: 2007-08-24
Posts: 191

Re: Tell if executing as root

it's probably just that the command in ticks `id -i` is being resolved before the "sudo echo $something" is run...

Offline

Board footer

Powered by FluxBB