简体   繁体   中英

BASH: Check if user is root

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 (ie creating a file in /)?

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"

Here, The below script will find the user is root or not.

#!/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

In the above example, I will try to create a file in the root directory, if I am not a root user and I don't have a permission it will give error, I was redirect that error to the /dev/null.

If the user have the permission, the file will be created. Then using the stat to get the user id for that file, and store that into the variable uid.

Using that variable in the if condition I will check.

If the temporary file will be created the rm command will remove that file.

But make sure the file is not already exist in the root directory.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM