5

I have a strange problem: In a GUI session, depending on the terminal being used the following two (related) problems appear:

  1. who and w doesn't list the user's active session
  2. logname returns logname: no login name

It happens in the following terminals:

  • lxterminal
  • xfce4-terminal
  • rxvt

On the other hand, in the following scenarios it works perfectly (who/w lists the user and logname functions):

  • ssh-ing in
  • xterm / lxterm / uxterm
3
  • haev you tried whoami? Feb 21, 2014 at 16:19
  • 1
    I want to get the user behind sudo. AFAIK the command for this is logname.
    – hyperknot
    Feb 21, 2014 at 16:20
  • Which shell are you running? sudo ps h -o cmd $$ | awk '{print $1}' | sed 's/\/bin\///'
    – Aaron
    Feb 21, 2014 at 16:53

2 Answers 2

1

The best answer I've found is here: https://stackoverflow.com/a/1629628/3196753

i.e.

echo ${SUDO_USER:-${USER}}

Or alternatively

logname 2>/dev/null || echo ${SUDO_USER:-${USER}}

FWIW, this works on MacOS 10.8, 10.11 and also confirmed as far back as Ubuntu 12.04.

The 2> is to suppress the logname: no login name error that will log to the console starting with Ubuntu 16.04 due to an upstream gnome-terminal bug.

:-${USER} means if $SUDO_USER is blank (for times when sudo is not actually being used), then substitute the value of $USER.

0

I have found the same problem in 16.04. I had several scripts using logname, and now they don't work. I've created a workaround. While logged in as myself, I drop a file in my home directory with my login username:

echo $LOGNAME > ~/.logname;

When I want to access my logname, I retreive it thus:

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

This works whether I am running a script as myself or as root, because sudo root maintains the definition of "~" as my home directory. I can create a .logname file for each user on the system. This method works, whereas using $USER and $LOGNAME do not when calling from a root level. True, someone could hack it and change the value in the file, but I'm not worried about that. You can always change the permissions on the file to 444 and the owner:group to root:root, which will stop anyone without root privileges.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.