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
2009-10-29 06:44:13
or, to keep it shorter check the UID env:if [[ $UID -ne 0 ]]; then
zlack
2009-10-29 08:44:12
@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
2010-02-04 00:15:03
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
2009-10-29 07:01:19
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
2009-10-29 07:04:43
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
2009-10-29 07:05:37