System and users
whoami
Print the user name of the effective user ID the current process runs as.
whoami
whoami looks up the effective user ID of the process and prints the matching user name.
It answers "whose permissions am I running with right now?", which after sudo, su or a
setuid program is not necessarily the person who logged in.
It is identical to id -un; id is the more general tool and also prints numeric IDs and
groups. In scripts, prefer checking the numeric ID (id -u or bash's $EUID) over the name:
root is always UID 0, but nothing stops an account from being renamed.
Examples
Print who you are
whoami
dev
The examples on this site run as the user dev.
Run it as root
whoami
root
The same command run by root prints root. Under sudo you would see this too, because
sudo changes the effective user.
Get the same answer from id
id -un
dev
id -un (user, name) is the equivalent id form; id -u gives the number instead.
Know that $USER is just a variable
USER=alice; echo "USER says $USER, whoami says $(whoami)"
USER says alice, whoami says dev
$USER is set by the login process and can be changed or missing (cron jobs and
containers often lack it). whoami asks the kernel for the effective UID, so it cannot be
fooled this way.
Refuse to run unless root
if [ "$(id -u)" -ne 0 ]; then
echo "$(basename "$0"): must be run as root, not $(whoami)" >&2
exit 1
fi
echo "doing root things"
bash: must be run as root, not dev
The check compares the numeric UID with 0 and the message uses the name. Run as dev, it
exits with status 1. ($0 is bash here because the snippet is run with bash -c.)
Compare with logname, which needs a login session
whoami; logname
dev logname: no login name
logname reports who logged in on the terminal, which survives su and sudo. With no
login session, as in this container or a cron job, it fails with no login name.
Common pitfalls
Scripts that check
[ "$USER" = root ].$USERmay be unset or stale aftersudo(depending on its configuration) and in cron; test"$(id -u)" -eq 0or$EUIDinstead.Expecting
whoamito show the original user aftersudo. It printsroot;$SUDO_USERorlognametell you who ran sudo.who am i(with spaces) is a different command, a form ofwhothat prints the login session of the terminal, and prints nothing when there is none.
GNU vs BSD and macOS
The examples above ran the GNU/Linux version. These are the differences that matter on macOS and the BSDs (written from their documentation, not run here).
Both GNU and BSD/macOS ship
whoami; the BSD man pages call it obsolete in favor ofid -un, which works everywhere.
Options worth knowing
A selection, described in our own words. For the full list, see whoami(1) or whoami --help.
| Option | What it does |
|---|---|
--help | Print usage and exit. |
--version | Print the coreutils version and exit. |