Preserve the Shell Environment Using sudo

When executing a command or script as another user, it may be necessary to preserve the current shell’s environment. sudo provides the -E flag for this.

However, on Ubuntu systems the PATH environment variable is not preserved by the -E flag. Work around this by passing the current shell’s PATH environment variable on the command-line in the form of PATH=$PATH.

$ sudo PATH=$PATH -E -u anotheruser ./

There are other ways to manage environment variables with sudo by editing /etc/sudoers (use sudoedit, don’t edit it directly!), but the above can be useful to quickly get the job done.

Tags: ,