我有一个安装了一些软件的bash脚本。如果它不是由root运行的话我想尽快失败。我怎么能这样做?
答案 0 :(得分:28)
#!/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
答案 1 :(得分:6)
在深入研究之后,似乎共识似乎是没有必要在bash中使用id -u
,因为将设置EUID
(有效用户ID)变量。与UID
相反,当用户为EUID
或使用0
时,root
将为sudo
。显然,这比运行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