Linux – Why doesn’t sudo -E actually preserve the environment

debianenvenvironment-variableslinuxsudo

I'm trying to sudo some binaries that lies in a custom path. That custom path is removed when I run sudo though, but sudo -E should preserve my path. Why doesn't it work?

$ env | egrep ^PATH
PATH=/home/codemonkey/.nvm/v0.6.1/bin:/usr/local/bin:/usr/bin:/bin:/usr/local/gam
es:/usr/games

$ sudo env | egrep ^PATH
PATH=/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin:/usr/X11R6/bin

$ sudo -E env | egrep ^PATH
PATH=/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin:/usr/X11R6/bin

I know how to work around it, I just want to know why sudo -E doesn't work

Best Answer

You can set the exempt_group option to tell sudo to keep the PATH for users in that group.

For example, say your user is in the group 'sys'. Add the following to your sudoers file

Defaults exempt_group="sys"

Now your user will not have PATH reset for sudo commands (-E is not needed for this to work).
See the man page for more details.

EDIT: Going to have to note this as a bad answer. It is true that it works, but it has a side effect I didnt notice while playing with it. It also exempts users in that group from having to type their password. Seems you cant get PATH preservation without allowing this. Bit stupid I think...