bash:如果root没有运行脚本,则会失败

时间:2009-10-29 06:41:49

标签: linux bash

我有一个安装了一些软件的bash脚本。如果它不是由root运行的话我想尽快失败。我怎么能这样做?

2 个答案:

答案 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

相关问题