Users – Difference Between logname and $LOGNAME

environment-variablesuserswhoami

While reading about environment variables, the one I came across was LOGNAME, I'd like to know the difference between this variable and whatever the command logname returns – as both of them did differ in what they returned.

-bash-3.2$ logname
user11
-bash-3.2$ echo $LOGNAME
user1

Although, whoami returns the same user as LOGNAME

-bash-3.2$ whoami
user1

Best Answer

logname goes up the user that owns the tty (by reading it from /var/run/utmp), while $LOGNAME is an env variable that contains the user that executes the current shell process. You can easily verify this with the following commands:

# ssh guido@localhost
# whoami
guido
# w
USER     TTY      FROM              LOGIN@   IDLE   JCPU   PCPU WHAT
guido    pts/3    localhost        13:02    0.00s  0.12s  0.03s sshd: guido [priv]
# echo $LOGNAME
guido
# sudo su
$ whoami
root
$ echo $LOGNAME
root
$ logname
guido
$ ps aux | grep bash
root      1145  0.5  0.1 110176  3604 pts/3    S    13:11   0:00 bash
root      1161  0.0  0.0 103304   844 pts/3    S+   13:11   0:00 grep bash
guido    28363  0.0  0.1 110048  3516 pts/3    Ss   13:02   0:00 -bash
Related Question