16

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?

3
  • 1
    Although 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. Commented 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 system Commented Oct 29, 2009 at 7:01
  • 1
    He 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. Commented Oct 29, 2009 at 7:04

2 Answers 2

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

Sign up to request clarification or add additional context in comments.

3 Comments

or, to keep it shorter check the UID env: if [[ $UID -ne 0 ]]; then
@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.
As pr1001 says, UID will not work if the user is running the script using sudo, but EUID will work just fine.
10

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

this doesn't work in the Bourne shell though. do you have any strictly POSIX compliant solutions?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.