Super User is a question and answer site for computer enthusiasts and power users. It's 100% free, no registration required.

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

I modified /etc/sudoers (using visudo) to keep environment variables :

Defaults        !env_reset

# Host alias specification

# User alias specification

# Cmnd alias specification

# User privilege specification
root    ALL=(ALL:ALL) ALL

# Members of the admin group may gain root privileges
%admin ALL=(ALL) ALL

# Allow members of group sudo to execute any command
%sudo   ALL=(ALL:ALL) ALL

#includedir /etc/sudoers.d
www ALL = NOPASSWD: /usr/bin/env

This works almost well : all environment variables are preserved, except PYTHONPATH !

www@myhost:~$ env | grep PYTHON
www@myhost:~$ sudo env | grep PYTHON

I tried to add that in sudoers :

Defaults        env_keep += "PYTHONPATH"

But it does not help.

I am using Ubuntu 11.10 : how to preserve PYTHONPATH ?

share|improve this question

You're very close: don't quote PYTHONPATH, as shown below.

Defaults    env_keep += PYTHONPATH

You don't need to modify env_reset.

You might also want to consider not changing sudoers at all. Instead, consider invoking sudo like this:

sudo PYTHONPATH=$PYTHONPATH <command...>

This also works with PATH and other variables. When expanded by the shell, you get literal paths as though you'd typed

sudo PYTHONPATH=/home/www/python_commons:... <command>

but only when you explicitly request to pass it (as opposed to implicitly with env_keep).

This works because sudo allows you to pass existing environment variables, which requires env_keep, or to specify env variables to be set solely for the sudo command, which does not require env_keep. Consider this:

snafu$ sudo grep Def /etc/sudoers
Defaults    env_reset
Defaults    env_keep += SE_ok
Defaults    env_keep += SE_ik

snafu$ SE_o=outer SE_ok=outer_keep sudo SE_i=inner SE_ik=inner_keep env | grep ^SE

This example demonstrates setting variables in sudo's calling environment (outer) and within sudo itself (inner). Note that SE_i is printed even though there's no env_keep entry for it. (env_keep for SE_ik is unnecessary.) Also note that env_keep does apply to outer variables (SE_o is not printed).

[Command invocations of the for 'var=val command' are equivalent to (export var=val; command). That is, they set one or more environment variables for that command only.]

share|improve this answer

Your Answer


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.