开发者

bash: fail if script is not being run by root

I have a bash script that 开发者_StackOverflow社区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

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜