From https://stackoverflow.com/a/29400598/156458
The other solutions I've seen here so far are based on some system definitions, but it's in fact possible to have
sudo
use the currentPATH
(with theenv
command) and/or the rest of the environment (with the-E
option) just by invoking it right:sudo -E env "PATH=$PATH" <command> [arguments]
In fact, one can make an alias out of it:
alias mysudo='sudo -E env "PATH=$PATH"'
(It's also possible to name the alias itself
sudo
, replacing the originalsudo
.)
Given that
-E, --preserve-env Indicates to the security policy that the user wishes to preserve their existing environment variables. The security policy may return an error if the user does not have permission to preserve the environment.
I was wondering why the following doesn't work
sudo -E <command> [arguments]
?
Given that "PATH=$PATH" <command> [arguments]
is also a command, I was wondering why the following doesn't work:
sudo "PATH=$PATH" <command> [arguments]
?
Thanks.
doesn't work
?" - Does sudo fail? Does the command not get the updated environment? Does it not match a sudoers entry? I think it'd also be useful to include the sudo configuration here regarding whitelist/blacklist/keep settings. – Jeff Schaller May 09 '18 at 13:08"PATH=$PATH" <command> [arguments]
is also a command..." is a false premise. It's not a command; it's an environment variable assignment followed by a command. Quoting aside, you could trysudo bash -c "PATH=... command args..."
. Just bear in mind thatcommand
would still need to be in your defaultsudo
value of$PATH
or else you'd need to use an explicit/path/to/command
– Chris Davies May 09 '18 at 22:25