logname
Print the user's login name
TLDR
Display the currently logged in user's name
SYNOPSIS
logname
DESCRIPTION
The logname
command is a simple utility that prints the name of the user who is currently logged in. Specifically, it retrieves the login name from the /var/run/utmp
file (or a similar system file that tracks user login sessions). This is often the name used to initially log into the system, although it may not always reflect the currently effective user ID, especially in environments with user switching (e.g., via su
). The output is simply the login name, followed by a newline character. It doesn't require any arguments to work and provides a quick way to identify the user's original login identity. It is often used in scripts or environments where knowing the initial login user is necessary, such as for logging purposes or access control.
CAVEATS
The output of logname
may not be accurate if the user has switched to a different user identity using commands like su
or sudo
. In such cases, whoami
or id -un
might provide a more accurate representation of the current effective user.
IMPLEMENTATION DETAILS
The logname
command typically reads from system files like /var/run/utmp
or similar files to determine the login name. The specific file and method used can vary depending on the operating system and its configuration.
In general the code opens the file, iterates over the logged-in users and prints the username, which is associated with the terminal.
HISTORY
The logname
command has been a standard utility in Unix-like operating systems for many years. It's origin is tied closely to the introduction of multi-user systems where tracking each user's login session became necessary. It was initially created to retrieve the username that authenticated the user.