Apr 24, 2009

The 'sudo' Command's Environment

I'm sure most people are aware the 'sudo' command sterilizes the user's environment variables before executing the command passed to it. The most common issue I've run into with this is $PATH not being preserved. The usual scenario is that I have an application installed into /opt and I've appended it's location to $PATH, which works just fine until you try to execute the application with 'sudo' and it fails because the command is no longer in the current path.

The fix to this is really straight forward and I'm surprised I hadn't thought of it earlier. Simply add the following to your $HOME/.bashrc file.

alias sudo="sudo env PATH=$PATH"
What this does is use 'sudo' to run 'env' which is passed the provided command but sets the target environment's PATH to match the current users before executing it.

Don't forget that you can always run the unaliased version of a command simply by prefixing it with a backslash.

3 comments:

Anonymous said...

Instead of passing the path through you could just use -E.

-E The -E (preserve environment) option will override the env_reset option in sudoers(5)). It is only available when either the matching command has the SETENV tag or the setenv option is set in sudoers(5).

And as this mentions you could just use setenv in your /etc/sudoers file.

Unknown said...

gregf: Thanks. I knew it was possible to fix by making changes in /etc/sudoers but hadn't taken the time to figure out how until you gave me this hint.

On the other hand even after figuring it out I'm staying with my approach. Mostly because I prefer to limit the scope of configuration file changes to my /HOME directory when possible.

It seems to make distribution upgrades less painful.

Tom said...

Helpful, thanks.