The Linux logname command is a simple utility that is part of the GNU Core Utilities. It has a single purpose, to print the name of the current user. There are no options and the command takes no arguments. You simply call it and it prints the current users login name.
$ logname mecherisi
The logname command should not be confused with the LOGNAME environmental variable. The LOGNAME enviornmental variable can be changed by the user as it is part of their enviornment. This is in contrast to the logname command, which uses the utmp/wtmp login records to pull the name of the current user.
There are plenty of tools that allow you to print the currently logged in user or users. Some offer a lot of options and switches, while others offer "effective" user identification. Some similar tools are whoami, who and w. Let's take a quick look at these commands and how they differ from the logname command.
The w command shows a lot more information about the user. It also displays a header and several columns of information. It has options and switches to change the base output. This is all good information, but sometimes you just need a simple answer. Here is an example of the output of the w command.
[[email protected] ~]$ w 00:12:11 up 4:16, 1 user, load average: 0.88, 1.02, 1.27 USER TTY [email protected] IDLE JCPU PCPU WHAT mecherisi :1 19:57 ?xdm? 59:02 0.00s /usr/libexec/gdm-x-session --run-script /usr/bin/gnome-session
Similarly, the who command also shows additional information. It also shows ALL the users logged into the system. This and the amount of options make it very different from the logname command.
[[email protected] ~]$ who mecherisi :1 2019-11-27 19:57 (:1) xguest :2 2019-11-27 13:45 (:2) savona :3 2019-11-27 12:33 (:3)
The whoami command actually shows you the "effective" user (euid). You can see that when we use sudo with whoami it returns root as the user. This is because when you run sudo, you are "effectively" root.
[[email protected] ~]$ whoami mecherisi [[email protected] ~]$ sudo whoami root
The logname command simply prints the name of the current user to STDOUT, nothing else. This comes in very handy if you are using it in a bash script and you just need the current user name.
[[email protected] ~]$ logname mecherisi [[email protected] ~]$ sudo logname mecherisi
Sometimes less it more. If you are writing a script and just need to get the current users name, logname is your friend. Of course you can do it with one of the other commands and use cut to trim the additional information. But, logname is the most direct, simplest and pure way to get that singular piece of information.
Resource and Links
This site uses Akismet to reduce spam. Learn how your comment data is processed.