Dav*_*own 28
#!/bin/bash
if [ "$(id -u)" != "0" ]; then
echo "This script must be run as root" 1>&2
exit 1
fi
Run Code Online (Sandbox Code Playgroud)
资料来源:http://www.cyberciti.biz/tips/shell-root-user-check-script.html
在深入研究之后,共识似乎是不需要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
Run Code Online (Sandbox Code Playgroud)
资料来源:https://askubuntu.com/questions/30148/how-can-i-determine-whether-a-shellscript-runs-as-root-or-not