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?
#!/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
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With