I'm writing a simple bash script, but I need it to check whether it's being run as root or not. I know there's probably a very simple way to do that, but I have no idea how.
Just to be clear:
What's a simple way to write a script foo.sh, so that the command ./foo.sh
outputs 0
, and the command sudo ./foo.sh
outputs 1
?
A root user does not have to be named "root".
whoami
returns the first username with user ID0
.$USER
contains the name of the logged in user, which can have user ID0
, but have a different name.The only reliable program to check whether the account is logged in as root, or not:
I use
-u
for the effective user ID, not-r
for the real user ID. Permissions are determined by the effective user ID, not the real one.Tests
/etc/passwd
contains the following usernames with user ID0
in the given order:Logged in as
root2
, gives the next results:whoami
:rootx
echo $USER
:root2
(this returns an empty string if the program was started in an empty environment, e.g.env -i sh -c 'echo $USER'
)id -u
:0
As you can see, the other programs failed in this check, onlyid -u
passed.The updated script would looks like this:
As @Lekensteyn said you should use effective user ID. You don't need to call
id -u
in bash:@geirha's suggestion from the comments uses arithmetic evaluation:
You can accomplish this by using the
whoami
command, which returns the current user:Running the above will print
You must be root to do this.
if the current user is notroot
.Note: an alternative in some cases is to simply check the
$USER
variable:Taking efficiency into consideration, you may test, first, the
EUID
environment variable and then, if it doesn't exist, call the standardid
command:This way, because of the OR shortcut, you avoid calling a system command, prioritizing the query of an in-memory variable.
Code reuse:
This snippet would:
sudo !!
This answer is just to save an idea with may be helpful for some of you. If you need script which is run from desktop GUI and requires root privileges try this way:
This way you will get nice dialog window asking you for root user password. Just like with command-line sudo.
The
gksudo
may not be available in your system then install it withsudo apt-get install gksu
.One simple way to make the script only runnable by root is to start the script with the line:
#!/bin/su root