bash:如果脚本不是由 root 运行,则失败
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/1641975/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
bash: fail if script is not being run by root
提问by flybywire
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?
我有一个安装一些软件的 bash 脚本。如果不是由 root 运行,我想尽快失败。我怎样才能做到这一点?
回答by David Brown
#!/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
回答by Tom
After digging around on this, the consensus seems to be that there is no need to use id -uin bash, as the EUID(effective user id) variable will be set. As opposed to UID, the EUIDwill be 0when the user is rootor using sudo. Apparently, this is around 100 times faster than running id -u:
在深入研究之后,共识似乎是不需要id -u在 bash 中使用,因为EUID(有效用户 ID)变量将被设置。相对于UID时,EUID将0当用户root或使用sudo。显然,这比运行快 100 倍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
来源:https: //askubuntu.com/questions/30148/how-can-i-determine-whether-a-shellscript-runs-as-root-or-not

