I have a use case where I want to sudo su - user1 to some user and then run script and in the script I want to fetch SUDO_USER. However the SUDO_* environment variables do not get set when I use sudo su - user1 instead of sudo su app.

sudo su user1
[sudo] password for rbhanot:
$ env | grep -i sudo
SUDO_COMMAND=/bin/su user1

If I invoke su with login shell these variables are not set

sudo su - user1
$ env|grep -i sudo

It works if I use a slightly different command with sudo -i

sudo -i -u user1
$ env|grep -i sudo

So why does these SUDO_* variables do not get with su - user1 specifically.

  • haven't read the code, but the manpage says the optional - is to "provide an environment similar to what the user would expect had the user logged in directly" and i wouldn't expect those variables to be set on a direct login
    – Fox
    Dec 17, 2020 at 5:38
  • Related: Is there ever a good reason to run sudo su?
    – Kusalananda
    Dec 17, 2020 at 7:25
  • @Kusalananda I know but still people use these interchangebly and hence the expected behaviour is different than actual one.
    – Rohit
    Dec 17, 2020 at 7:57
  • 1
    Then they may want to change their expectation, or their behavior. For example, in this case you may want to use sudo -i instead, or not rely on those variables being set. Or, you could change your question to not be about sudo at all and ask why su - clears the environment.
    – Kusalananda
    Dec 17, 2020 at 8:13
  • sudo su Considered Harmful. Read man sudo sudoers su.
    – waltinator
    Dec 17, 2020 at 20:11

1 Answer 1


Try it without the -i and the variables should go across for you.

If that doesn't work, you might consider having them specify the variables on the command line? Maybe not ideal, but it would give the users the flexibility you want..

ie.  sudo -i -u joe SUDO_GID=4361 SUDO_UID=4361 SUDO_USER=rbhanot /bin/ksh

If that's a bit much for the users to remember, you can add an alias for it in their .bash_profile.

ie.  alias myroot="sudo -i -u joe SUDO_GID=4361 SUDO_UID=4361 SUDO_USER=rbhanot /bin/ksh"

Then they simply type "myroot" and it will run the sudo command as written.

You must log in to answer this question.

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