How to Fix sudo Missing Environment Variables on Linux
When using sudo, Linux resets the environment, causing custom variables to disappear; this guide explains why, shows the relevant lines in /etc/sudoers, and presents three practical methods—including sudo -E, editing env_keep and secure_path, and creating aliases—to retain needed variables.
Background
When a command is executed with sudo, the environment is reset to a safe default; custom variables disappear unless explicitly preserved.
Configuration File
The sudo configuration resides in /etc/sudoers and requires root privileges to read or edit.
sudo sed '/^#/d;/^$/d' /etc/sudoersKey Directives
Defaults env_reset (line 3) enables the default environment reset.
Lines 4‑8 contain env_keep entries; variables listed inside double quotes are retained.
Line 9 defines secure_path , which sets the PATH used by sudo. Adding missing command directories here allows sudo to locate them.
Methods to Preserve Variables
Use the -E option: sudo -E command runs the command with the caller’s environment unchanged. This may fail if the user lacks permission for certain variables.
Edit /etc/sudoers to adjust env_keep and secure_path so required variables and paths are retained.
Manually set variables before invoking sudo or create an alias that injects the current PATH , e.g., alias sudo='sudo env PATH=$PATH' . Disabling the reset entirely can be done by changing Defaults env_reset to Defaults !env_reset and handling PATH in .bashrc .
Reference URLs
https://www.google.com
http://ghoulich.xninja.org/2017/05/09/how-to-find-env-variables-when-exec-sudo-commands/
http://www.ibm.com/developerworks/cn/aix/library/au-sudo/index.html
Signed-in readers can open the original source through BestHub's protected redirect.
This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactand we will review it promptly.
Liangxu Linux
Liangxu, a self‑taught IT professional now working as a Linux development engineer at a Fortune 500 multinational, shares extensive Linux knowledge—fundamentals, applications, tools, plus Git, databases, Raspberry Pi, etc. (Reply “Linux” to receive essential resources.)
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.
