简体   繁体   English

bash:如果root没有运行脚本,则会失败

[英]bash: fail if script is not being run by root

I have a bash script that installs some software. 我有一个安装一些软件的bash脚本。 I want to fail as soon as possible if it is not being run by root. 如果它不是由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 资料来源: 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. 在深入研究之后,似乎共识似乎是不需要在bash中使用id -u ,因为将设置EUID (有效用户id)变量。 As opposed to UID , the EUID will be 0 when the user is root or using sudo . UID相反,当用户是root或使用sudo时, EUID将为0 Apparently, this is around 100 times faster than running id -u : 显然,这比运行id -u快约100倍:

#!/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 资料来源: https//askubuntu.com/questions/30148/how-can-i-determine-whether-a-shellscript-runs-as-root-or-not

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM