Preserve Environment Variables When Using Sudo in Ubuntu
When executing commands with elevated privileges in Ubuntu, the sudo utility typically resets environment variables for security reasons. This article explains why this happens and provides practical methods to preserve specific variables or the entire environment when necessary. You will learn how to use command-line flags and configure the sudoers file safely to maintain your session settings while running administrative tasks.
By default, sudo strips most environment variables to prevent users
from accidentally or maliciously altering the root environment. This
security measure ensures that privileged commands run in a predictable
state. However, certain workflows require specific variables, such as
PATH, HOME, or custom application settings, to
persist during elevation.
Use the -E Flag
The simplest method to preserve your existing environment is using
the -E or --preserve-env flag. This tells sudo
to keep the current user’s environment variables when running the
command.
sudo -E command_nameFor example, to run a script while keeping your current
PATH and custom variables:
sudo -E ./setup_script.shNote that some variables may still be overridden by sudo’s security policies unless explicitly allowed in the configuration.
Pass Specific Variables
If you only need to preserve or set specific variables, you can define them directly before the command. This method is cleaner than preserving the entire environment.
sudo VAR_NAME=value command_nameYou can also preserve an existing variable by referencing it:
sudo MY_VAR=$MY_VAR command_nameConfigure the Sudoers File
For a permanent solution that allows specific variables to persist
without using flags every time, you must edit the sudoers file. Always
use the visudo command to edit this file, as it checks for
syntax errors before saving.
sudo visudoLocate the Defaults section and add the
env_keep setting. For example, to always preserve the
PYTHONPATH variable:
Defaults env_keep += "PYTHONPATH"
You can add multiple variables by separating them with spaces within the quotes. After saving and exiting, sudo will automatically retain these variables for all users with sudo privileges.
Security Considerations
Preserving environment variables can introduce security risks.
Malicious variables could alter library paths or executable locations,
potentially allowing privilege escalation. Only preserve variables that
are absolutely necessary for your task. Avoid using the -E
flag or env_keep for variables related to dynamic linkers
or shell configurations unless you fully trust the commands being
executed.