Ubuntu – “sudo pip” differs from normal “pip”


When I execute

which pip3

it points to


However, when I run

sudo which pip3

the result is


Where does this problem comes from and how do I achieve that sudo pip also points to /usr/.../anaconda3/bin/pip3?

Best Answer

sudo sanitizes the environment before running any command. In doing so, if the value of the directive secure_path is set, it will be used as the PATH for the sudo commands, not the current PATH.

In my system:

% sudo grep -E 'secure_path' /etc/sudoers
Defaults    secure_path="/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin"

So i have:

% echo $PATH

% sudo bash -c 'echo $PATH' 

What you can do to keep your current path or add /usr/.../anaconda3/bin to sudo's PATH:

  • Pass PATH in the environment of the which command:

    sudo PATH="$PATH" which pip3

    Any desired PATH can be set too.

  • Keep the current environment while running sudo by:

    sudo -E which pip3
  • Disable the secure_path value by putting a # in front or remove the line to keep the current PATH:

    # Defaults        secure_path="....."   

    Instead, you can also modify the secure_path to just add /usr/.../anaconda3/bin to it, at the beginning.

  • Add PATH to the env_keep directive to keep the PATH in the sudo provided environment:

    Defaults        env_keep += "PATH"