How to set path for sudo commands

39

14

If I issue

sudo my-command

how does Linux look for that my-command?

The my-command is in my PATH. I can invoke it without any problem. However, when I invoke it with sudo, I'll get command not found. Interesting, never experience this before. How to overcome?

EDIT: That "Possible duplicate"'s selected answer is wrong, well, at least not to the point. This answer, from terdon, is the correct one.

xpt

Posted 2015-06-13T16:43:36.003

Reputation: 5 548

Answers

50

This is normally set by the secure_path option in /etc/sudoers. From man sudoers:

 secure_path   Path used for every command run from sudo.  If you don't
               trust the people running sudo to have a sane PATH environ‐
               ment 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 by secure_path.  This option is not
               set by default.

To run commands that are not in the default $PATH, you can either

  1. Use the full path: sudo ~/bin/my-command; or

  2. Add the directory containing the command to secure_path. Run sudo visudo and edit the secure path line:

    Defaults        secure_path="/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin:/home/youruser/bin/"
    

    Save the file and next time you run sudo, the directory ~/bin will be in its $PATH.

terdon

Posted 2015-06-13T16:43:36.003

Reputation: 45 216

3Or just comment out the whole line if this isn't a production machine and we don't care. Then it will use the users' PATH. It says that it's not set by default, but that may not always be true... – Nagev – 2019-01-30T10:11:06.957

3

This is what I used for a workaround:

sudo cp $(which my-command) /usr/bin
...

The which command is executed in a subshell that is non-root, so it is able to find my-command, then, sudo copies the executable to a path that the root user can access. Not great for security, but it was ok for me running a docker image that was being destroyed right after the command was run.

Brenden Smith

Posted 2015-06-13T16:43:36.003

Reputation: 31