[英]bash: fail if script is not being run by root
我有一个安装一些软件的bash脚本。 如果它不是由root运行的话我想尽快失败。 我怎样才能做到这一点?
#!/bin/bash
if [ "$(id -u)" != "0" ]; then
echo "This script must be run as root" 1>&2
exit 1
fi
资料来源: http : //www.cyberciti.biz/tips/shell-root-user-check-script.html
在深入研究之后,似乎共识似乎是不需要在bash中使用id -u
,因为将设置EUID
(有效用户id)变量。 与UID
相反,当用户是root
或使用sudo
时, EUID
将为0
。 显然,这比运行id -u
快约100倍:
#!/bin/bash
if (( EUID != 0 )); then
echo "You must be root to do this." 1>&2
exit 1
fi
资料来源: 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.