BASH: Check if user is root

时间:2015-10-30 23:34:49

标签: linux bash root privileges

How can I check whether a user is root or not within a BASH script? I know I can use [[ $UID -eq 0 ]] || echo "Not root" or [[ $EUID -eq 0 ]] || echo "Not root" but if the script was invoked via fakeroot, UID and EUID are both 0 (of course, as fakeroot fakes root privileges). But is there any way to check whether the user is root? Without trying to do something only root can do (i.e. creating a file in /)?

2 个答案:

答案 0 :(得分:7)

Fakeroot sets custom LD_LIBRARY_PATH that contains paths to libfakeroot. For example: /usr/lib/x86_64-linux-gnu/libfakeroot:/usr/lib64/libfakeroot:/usr/lib32/libfakeroot You can use this to detect if application is running inside the fakeroot iterating by paths and looking for libfakeroot. Sample code: IS_FAKEROOT=false for path in ${LD_LIBRARY_PATH//:/ }; do if [[ "$path" == *libfakeroot ]]; then IS_FAKEROOT=true break fi done echo "$IS_FAKEROOT"

答案 1 :(得分:-1)

在这里,下面的脚本会发现用户是否为root用户。

#!/bin/bash
touch /checkroot 2>/dev/null

uid=`stat -c "%u" /checkroot 2>/dev/null`

if [ "$uid" = "0" ]
then
    echo "Root user"

else
    echo "Not a root user"
fi

rm /checkroot 2>/dev/null

在上面的例子中,我将尝试在根目录中创建一个文件,如果我不是root用户并且我没有权限它会给出错误,我将该错误重定向到/ dev /空。

如果用户拥有该权限,则将创建该文件。然后使用stat获取该文件的用户ID,并将其存储到变量uid中。

在if条件中使用该变量,我将检查。

如果要创建临时文件,rm命令将删除该文件。

但请确保根目录中尚不存在该文件。