Can I make `sudo` follow my path via CLI?

You can edit sudoers file and set secure_path to match your path. This is documented in Unix & Linux.

Is there a command line switch I can pass to sudo such that it uses the path I have set? For example:

rick@alien:~$ sudo echo $PATH
/home/rick/bin:/home/rick/.local/bin:/mnt/e/bin:/mnt/e/usr/local/bin:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin:/usr/games:/usr/local/games:/snap/bin
───────────────────────────────────────────────────────────────────────────────
rick@alien:~$ echo $PATH
/home/rick/bin:/home/rick/.local/bin:/mnt/e/bin:/mnt/e/usr/local/bin:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin:/usr/games:/usr/local/games:/snap/bin
───────────────────────────────────────────────────────────────────────────────
rick@alien:~$ sudo which auto-brightness-config
/usr/local/bin/auto-brightness-config
───────────────────────────────────────────────────────────────────────────────
rick@alien:~$ which auto-brightness-config
/mnt/e/usr/local/bin/auto-brightness-config
───────────────────────────────────────────────────────────────────────────────
rick@alien:~$ sudo locate auto-brightness-config
/Desktop/Link to auto-brightness-config
/home/rick/Pictures/display-auto-brightness-config 1.png
/mnt/e/Desktop/Link to auto-brightness-config
/mnt/e/usr/local/bin/.auto-brightness-config
/mnt/e/usr/local/bin/Link to auto-brightness-config
/mnt/e/usr/local/bin/auto-brightness-config
/usr/local/bin/.auto-brightness-config
/usr/local/bin/Link to auto-brightness-config
/usr/local/bin/auto-brightness-config

When I run using sudo it is finding the wrong copy of the script in /usr/local/bin when I really want the version in /mnt/e/usr/local/bin .

If I don't want to maintain the path in sudoers file, is there a switch I can pass to sudo to use my path to find the right command?


Solution 1:

Ubuntu by default already has secure_path set:

~ sudo -l
Matching Defaults entries for muru on muru-1604:
    env_reset, mail_badpass, secure_path=/usr/local/sbin\:/usr/local/bin\:/usr/sbin\:/usr/bin\:/sbin\:/bin\:/snap/bin    
User muru may run the following commands on muru-1604:
    (ALL : ALL) ALL

There is no command-line option that can override secure_path set in 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
               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 by secure_path.  This
               option is not set by default.

So either set exempt_group in sudoers and add yourself to that group, or exempt yourself from sudoers:

Defaults:rick !secure_path

(rick presumably being your username.)