我有一个安装某些软件的Bash脚本。如果它没有以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
sudo
运行脚本时给出原始用户的UID,而David的则将脚本视为以root身份运行。根据你要做什么,David的可能更好。 - pr1001在这方面进行深入挖掘后,一致的看法似乎是在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
如何确定shell脚本是否以root身份运行:
您可以使用以下代码:
if [ "$(id -u)" != "0" ]; then
echo "This script must be run as root" 1>&2
exit 1
fi
这将检查当前用户的UID是否为0(即root)。如果不是,则输出错误消息并退出脚本。