Why are PATH variables different when running via sudo and su?
Take a look at /etc/sudoers
. The default file in Fedora (as well as in RHEL, and also Ubuntu and similar) includes this line:
Defaults secure_path = /sbin:/bin:/usr/sbin:/usr/bin
Which ensures that your path is clean when running binaries under sudo. This helps protect against some of the concerns noted in this question. It's also convenient if you don't have /sbin
and /usr/sbin
in your own path.
The command su -
will execute the root users profile and take on that user's environment including path etc. sudo
does not do that.
If you'd like sudo
to behave like su -
then use the option sudo -i [command
which will execute the user's profile
If you'd like su -
to behave like sudo
then don't use the hyphen - just use su [command]
You can check why (it's different) by running sudo sudo -V
.
For example on Linux run:
$ sudo sudo -V | grep PATH
Value to override user's $PATH with: /usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin
Note: On macOS/BSD, just run: sudo sudo -V
.
The above list is restricted due to default security policy plugin in some Linux distributions.
This is further explained in man sudoers
:
If the
secure_path
option is set, its value will be used for thePATH
environment variable.
secure_path
- Path used for every command run from sudo. If you don't trust the people running sudo to have a sanePATH
environment variable you may want to use this.Another use is if you want to have the “root path” be separate from the “user path”. Users in the group specified by the
exempt_group
option are not affected bysecure_path
. This option is not set by default.
If that's the case, you can change that by running sudo visudo
and editing the configuration file and modifying your secure_path
(adding extra path separated by :
) or add your user into exempt_group
(so you won't be affected by secure_path
options).
Or in order to pass user's PATH
temporary, you can run:
sudo env PATH="$PATH" my_command
and you can check that by:
sudo env PATH="$PATH" env | grep ^PATH
See also: How to make sudo
preserve $PATH
?
Other reason why the environment could be different for sudo
, is because you could have env_reset
option enabled in your sudoers
file. This causes commands to be executed with a new, minimal environment.
So you can use env_keep
option (not recommended for security reasons) to preserve your user's environment variables:
Defaults env_reset
Defaults env_keep += "PATH PYTHONPATH"