Operations 4 min read

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.

Liangxu Linux
Liangxu Linux
Liangxu Linux
How to Fix sudo Missing Environment Variables on Linux

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/sudoers

Key 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

sudo configuration
sudo configuration
Original Source

Signed-in readers can open the original source through BestHub's protected redirect.

Sign in to view source
Republication Notice

This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactadmin@besthub.devand we will review it promptly.

LinuxSystem AdministrationBashEnvironment VariablesSudosudoers
Liangxu Linux
Written by

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.)

0 followers
Reader feedback

How this landed with the community

Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.