Skip to content
Advertisement

BASH: Check if user is root even when using fakeroot [duplicate]

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 /)?

Advertisement

Answer

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"
User contributions licensed under: CC BY-SA
4 People found this is helpful
Advertisement