Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

bash: fail if script is not being run by root

Tags:

linux

bash

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?

like image 501
flybywire Avatar asked Oct 29 '09 06:10

flybywire


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

like image 86
David Brown Avatar answered Oct 19 '22 19:10

David Brown


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

like image 9
Tom Avatar answered Oct 19 '22 17:10

Tom