tags:

views:

122

answers:

2

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?

+9  A: 
#!/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

David Brown
or, to keep it shorter check the UID env:if [[ $UID -ne 0 ]]; then
zlack
@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.
pr1001
A: 

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

masterLoki
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.
Tim Post
However, if this gets down-voted, I'm not the one that did it :) Its pretty clear that you mis-read the original question.
Tim Post