Persisting Local Environment Variables When Running sudo

Album Cover: Begin To Hope

"On the radio, you hear November Rain. That solo's awful long, but it's a good refrain."
Regina Spektor / On The Radio

Posted on December 23, 2013 7:09 PM in Computers
Warning: This blog entry was written two or more years ago. Therefore, it may contain broken links, out-dated or misleading content, or information that is just plain wrong. Please read on with caution.

At work I ran into a situation where I needed to be able to set a local environment variable and still have that environment variable be accessible when I ran various scripts with sudo privileges. After researching the issue as I normally do, I realized that while the information is out there, buried and unfortunately veiled in various forum responses, there really isn't a clear and concise explanation of how to achieve such a thing.

I run Linux Mint, which is very similar to Ubuntu, so this approach should work on either of the two flavors. The key to ensuring specific local variables persist when you make use of sudo privileges is to make use of the env_keep directive. Rather than editing the /etc/sudoers file directly, I looked at its contents and realized that it includes files from the /etc/sudoers.d directory, so I created a new file specifically for the purpose of persisting specific local environment variables. I created a file at /etc/sudoers.d/env_vars with the following contents:

Defaults    env_keep += "my_env_var_to_persist"

After doing that, I ran sudo -l to verify that the Defaults entry I added took effect and noticed a complaint about the access permissions on the new file I created. Since the message asserted that the permissions should be 0440 on the file, I quickly remedied the situation:

sudo chmod 0440 /etc/sudoers.d/env_vars

Once I did that, I ran sudo -l again, verified that the permissions on the new file were no longer an issue, and saw that my new env_keep directive was included among my Defaults entries when running with sudo permissions. Now, any time I set my_env_var_to_persist as a local environment variable, e.g.:

export my_env_var_to_persist='lodi dodi'

...when I make a subsequent call to a script or process with sudo, that environment variable persists and I can make use of it however I see fit. A nice simple example of this is calling sudo env. Try it for yourself and feel the magic!

Gob's Magic


nxvjdchn on July 18, 2015 at 4:56 PM:
mamrwycj on May 15, 2017 at 5:22 AM:

Post Comments

If you feel like commenting on the above item, use the form below. Your email address will be used for personal contact reasons only, and will not be shown on this website.


Email Address:



Check this box if you hate spam.