Difference between $LOGNAME and logname

From Environment variables:

$LOGNAME is same as $USER which gives

The name of the currently logged-in user. This variable is set by the system. You probably shouldn't change its value manually.

From man logname:

logname - print user´s login name


Explained differently used by following example:

pandya@pandya-desktop:~$ sudo su
root@pandya-desktop:/home/pandya# echo $LOGNAME
root
root@pandya-desktop:/home/pandya# logname
pandya
root@pandya-desktop:/home/pandya# exit
exit
pandya@pandya-desktop:~$

Here you can see the difference after logging as root in a terminal,

  • $LOGNAME gives the name of the currently logged-in user in the terminal (i.e root)
  • Whereas logname prints the user's login name who logged in to the session (i.e. pandya)

The utility logname is broken in 16.04, apparently on purpose because it's possible to hack the value it returns, which could be a security flaw. https://bugzilla.gnome.org/show_bug.cgi?id=747046 I had been using logname in some scripts, and found it useful because it always returned the same value (my login name) whether I was calling it from from a my own level or from a sudo invocation, whereas the environment variables $USER and $LOGNAME do not. I wasn't worried about someone hacking into my computer and modifying the value it returns. Alas.... I have found a workaround. I created a file in my home directory as such

echo $USER > ~/.logname

When I want to access my logname (e.g., assigning to a Bash variable g_logname), I do so thusly:

declare g_logname="$(<~/.logname)";

This works for me, whether as myself or at the root level through sudo, which maintains the assignment of "~" as my home directory. I can create a .logname file for the home directory of each user on the system. Yes, someone could hack into my computer and change these files, but I'm not really worried about that. I just want my scripts to work.