System
logname
Print the login name of the current user.
userloginidentitywhoami
Additional Notes
logname prints the name of the user who initially logged into the current terminal session. Unlike whoami (which returns the effective user ID) and id -un (which also returns the effective username), logname always shows the original login name, regardless of su, sudo, or other user-switching commands.
It works by reading the /var/run/utmp or /var/log/wtmp file, or by checking the LOGNAME environment variable.
Syntax
logname [options]
Parameters
options: Flags that change howlognamebehaves.target: Optional file, device, interface, user, service, or command target when the command supports one.
Common Options
--help: Display help and exit.--version: Output version information and exit.
Examples
logname
Output: rani (the original login user).
sudo su
logname
Even after switching to root, logname still shows the original login name.
echo $(logname)
Use in a command substitution to capture the login name.
Practical Notes
lognamediffers fromwhoamiandid -unwhen privileges have been escalated. If you are root viasudo,whoamishowsroot, butlognameshows the original user.- If the login name cannot be determined,
lognameexits with a non-zero status and prints an error. - The
LOGNAMEenvironment variable is set by the login process and is not always reliable if tampered with.