Why can't I sudo some commands? (e.g., vim)
When running sudo
, many systems are configured to clear the environment of all non-whitelisted values, and to reset the PATH variable to a sanitized value.
You will find the former as Defaults env_reset
and several Defaults env_keep += "SOME_VARIABLE_NAME"
in /etc/sudoers
. The latter "secure" PATH
override is specified as Defaults secure_path = /sbin:/bin:/usr/sbin:/usr/bin
– delete this line to remove this behavior when sudo
ing.
How which environment variable is handled is printed when you run sudo -V
as root
.
If you don't want to get rid of these defaults, you can always specify programs using their full path (sudo /usr/local/bin/vim
).
Alternatively, you can allow your account to SETENV
in the sudoers
file, for example:
%wheel ALL=(ALL) SETENV: ALL
This allows you to override environment defaults like this: sudo PATH=$PATH which vim
, as the variable is intepreted by your shell before the command is executed, resulting in an inherited PATH
(which will likely not include /sbin
etc. though).
sudo echo $PATH
does not do what you think. $PATH
gets replaced by the (your) shell before execuitng the command.
To accomplish the desired behavior, you can use sudo -i
.
From man sudo:
-i [command]
The -i (simulate initial login) option runs the shell specified in the passwd(5) entry of the target user as a login shell. This means that login-specific resource files such as
.profile
or.login
will be read by the shell. If a command is specified, it is passed to the shell for execution.
How do I get
sudo <command>
to work?
Until you resolve the problem with paths use a full pathname
sudo /usr/local/bin/vim /var/www/html/index.html