Who sets $USER and $USERNAME environment variables

environment-variables

Also, will these variables always match currently logged-in username (they do on my Debian system)? Can I assume their availability in other Unix(-like) systems?

I'm also curious why one would use whoami instead of just reading any of these variables.

Best Answer

It's login.

The Linux login(1) man page says:

The value for $HOME, $USER, $SHELL, $PATH, $LOGNAME, and $MAIL are set according to the appropriate fields in the password entry.

The FreeBSD login(1) man page says:

The login utility enters information into the environment (see environ(7)) specifying the user's home directory (HOME), command interpreter (SHELL), search path (PATH), terminal type (TERM) and user name (both LOGNAME and USER).

The NetBSD, OpenBSD and OS X man pages say the same thing.

Here's the source code from the util-linux login:

setenv("HOME", pwd->pw_dir, 0); /* legal to override */
setenv("USER", pwd->pw_name, 1);
setenv("SHELL", pwd->pw_shell, 1);
/* ... */
setenv("LOGNAME", pwd->pw_name, 1);

Here's the source code from the FreeBSD login:

(void)setenv("LOGNAME", username, 1);
(void)setenv("USER", username, 1);
(void)setenv("PATH", rootlogin ? _PATH_STDPATH : _PATH_DEFPATH, 0);
Related Question