Take the 2-minute tour ×
Super User is a question and answer site for computer enthusiasts and power users. It's 100% free, no registration required.

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 stackoverflow.com Jun 25 '11 at 10:12

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

2 Answers 2

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:

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

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 -
Password:
[root@localhost ~]# echo $WHOAMI
corman
[root@localhost ~]# logout
[corman@localhost ~]$ su -
Password:
[root@localhost ~]# echo $WHOAMI
corman
[root@localhost ~]#
share|improve this answer
    
Most excellent, thank you! –  Scott Jun 25 '11 at 6:51
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!

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

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

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