I have a bash script that installs some software. I want to fail as soon as possible if it is not being run by root. How can I do that?
-
1Although I would generally consider this silly behavior: Let it run until permissions fail; the system may be setup such that the operation can be performed successfully as the current user and by forcing root this option is taken away [I've had to fix scripts that have made similar assumptions before]. On the other hand, I such much more of a case to prevent access or display a big fat warning if run as root.user166390– user1663902009-10-29 06:55:59 +00:00Commented Oct 29, 2009 at 6:55
-
You should try using sudo. Under linux, when you install anything you need to be root to prevent normal users installing anything that may damage the systemEligio Becerra– Eligio Becerra2009-10-29 07:01:19 +00:00Commented Oct 29, 2009 at 7:01
-
1He wants his script to take into account that some people may forget, or be unaware of sudo (or other means of privilege escalation). Its good practice to check for run time sanity before attempting to do anything else.user50049– user500492009-10-29 07:04:43 +00:00Commented Oct 29, 2009 at 7:04
Add a comment
|
2 Answers
#!/bin/bash
if [ "$(id -u)" != "0" ]; then
echo "This script must be run as root" 1>&2
exit 1
fi
Source: http://www.cyberciti.biz/tips/shell-root-user-check-script.html
3 Comments
zlack
or, to keep it shorter check the UID env: if [[ $UID -ne 0 ]]; then
pr1001
@zlack $UID will give the original user's UID if the script is run via
sudo while David's will consider the script as being run as root. Depending on what you're doing, David's is probably better.Tom
As pr1001 says, UID will not work if the user is running the script using sudo, but EUID will work just fine.
After digging around on this, the consensus seems to be that there is no need to use id -u in bash, as the EUID (effective user id) variable will be set. As opposed to UID, the EUID will be 0 when the user is root or using sudo. Apparently, this is around 100 times faster than running id -u:
#!/bin/bash
if (( EUID != 0 )); then
echo "You must be root to do this." 1>&2
exit 1
fi
Source: https://askubuntu.com/questions/30148/how-can-i-determine-whether-a-shellscript-runs-as-root-or-not
1 Comment
Janus Troelsen
this doesn't work in the Bourne shell though. do you have any strictly POSIX compliant solutions?