A root user does not have to be named "root". whoami returns the first username with user ID 0. $USER contains the name of the logged in user, which can have user ID 0, but have a different name.
The only reliable program to check whether the account is logged in as root, or not:
id -u
I use -u for the effective user ID, not -r for the real user ID. Permissions are determined by the effective user ID, not the real one.
Tests
/etc/passwd contains the following usernames with user ID 0 in the given order:
rootx
root2
Logged in as root2, gives the next results:
whoami: rootx
echo $USER: root2 (this returns an empty string if the program was started in an empty environment, e.g. env -i sh -c 'echo $USER')
id -u: 0
As you can see, the other programs failed in this check, only id -u passed.
The updated script would looks like this:
#!/bin/bash
if ! [ $(id -u) = 0 ]; then
echo "I am not root!"
exit 1
fi
$UIDandid -ruare still 0, but$EUIDandid -uaren't. Seegetuid(2)and decide what you need. – David Foerster Oct 16 '14 at 09:26$UIDand$EUIDare bashisms. Merely POSIX compliant shells don't have those variables and you need to useid(1)instead. – David Foerster Oct 16 '14 at 09:28if ((EUID)); then, see @geirha's comment – jfs Oct 17 '14 at 19:38echo $EUIDas the first 'normal' user gives me1000(expected). Runningsudo echo $EUIDgives me1000(not expected). On the other hand,id -ugives me1000, andsudo id -ugives me0(both expected). – Andrew Ensley Oct 16 '15 at 15:17sudo. If you runsudo sh -c 'echo $EUID'you will see your expected results. – sourcenouveau Nov 19 '15 at 18:09sudo sh -c 'echo $EUID'gives me a blank line. I should see0. – Andrew Ensley Nov 19 '15 at 18:12$EUIDis a Bashism (as mentioned above by @DavidFoerster), and your/bin/shis most likely a link to/bin/dash, not/bin/bash.sudo bash -c 'echo $EUID'will yield the expected result. – Adrian Günter May 09 '17 at 21:40/bin/bash, many (all?) Bash installs will run in POSIX mode if called assh. That is, they'll intentionally ignore Bashisms. It's useful as a first-pass test if you're trying to write POSIX-compliant shell scripts, but can cause issues if you're usingsh -cto delay interpolation. – Jun 12 '19 at 17:30[[ $EUID -ne 0 ]] && echo "non-root" || echo "root"– fcole90 Aug 28 '21 at 08:54