When I SSH into a Linux box, I want to have the /etc/profile file save the results of the whoami command to a global environment variable.

If I were to go root with the command sudo su -, I do not want that command to run again when going root. I want it to use the result of whoami with my regular username from before I went root, and need to access that variable as the root user even though it will run the /etc/profile file again when I go root.

What can I do to only run that command once in the /etc/profile command?

migrated from stackoverflow.com Jun 25 '11 at 10:12

This question came from our site for professional and enthusiast programmers.


Preserving environment variables past a login shell requires the -m switch. Preserving environment variables past sudo requires a change to env_keep in /etc/sudoers. Even then, doing this is iffy.

Fortunately, there are other ways to go about this. For example, your tty is owned by the user you initially logged in as. So adding this to the end of /etc/profile:

if [ -n "$TTY" ]; then
    WHOAMI=`ls -al $TTY | awk '{print $3}'`

You'll set the WHOAMI variable to the owner of the tty, if there is one, past both sudo and non-sudo su to root:

[corman@localhost ~]$ sudo su -
[root@localhost ~]# echo $WHOAMI
[root@localhost ~]# logout
[corman@localhost ~]$ su -
[root@localhost ~]# echo $WHOAMI
[root@localhost ~]#
  • 2
    A bit cleaner to write WHOAMI=$(stat --format="%U" "$TTY") – glenn jackman Jun 25 '11 at 10:59

You may also use logname instead of whoami!

  • +1. whoami gets confused when sudo elevations are in place, and some scripts really need logname to just know who invoked the script, like when changing broken file ownership back to the calling user... rather than inadvertently changing them to "root". – Vlueboy Jun 26 '11 at 8:24

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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