Super User is a question and answer site for computer enthusiasts and power users. Join them; it only takes a minute:

Sign up
Here's how it works:
  1. Anybody can ask a question
  2. Anybody can answer
  3. The best answers are voted up and rise to the top

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?

share|improve this question

migrated from Jun 25 '11 at 10:12

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

up vote 5 down vote accepted

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 ~]#
share|improve this answer
Most excellent, thank you! – Scott Jun 25 '11 at 6:51
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!

share|improve this answer
+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

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .