0

I'm confused by the following:

[user@QVr740-11 ~]$ which ninja
/usr/local/bin/ninja
[user@QVr740-11 ~]$ sudo which ninja
which: no ninja in (/sbin:/bin:/usr/sbin:/usr/bin)
[user@QVr740-11 ~]$ sudo echo $PATH
/usr/local/bin:/usr/bin:/usr/local/sbin:/usr/sbin:/home/user/.local/bin:/home/user/bin

ls -l /usr/local/bin/ninja shows that the binary is owned by root:root, and executable by all (three x's), and $PATH shows that even as sudo, it should be in the path, however when I go to execute which, the path has somehow changed.

sudo -E does not change this behaviour.

What gives? Is $PATH being preserved? Is which looking elsewhere for a path (note that I can't execute this binary as sudo).

Jeff Schaller
  • 67,283
  • 35
  • 116
  • 255
  • Relating https://unix.stackexchange.com/questions/83191/how-to-make-sudo-preserve-path and https://unix.stackexchange.com/questions/8646/why-are-path-variables-different-when-running-via-sudo-and-su – Jeff Schaller Aug 23 '21 at 17:27

2 Answers2

2

There are two issues here

  1. The $PATH variable is being expanded before the command is run. The net result is that you get this, which while being valid isn't really what you're wanting:

    sudo echo /usr/local/bin:/usr/bin:/usr/local/sbin:/usr/sbin:/home/user/.local/bin:/home/user/bin
    
  2. The $PATH is usually reset by sudo for security reasons

You could use sudo env | grep ^PATH= to find the $PATH value in the context of sudo running an application. You can adjust the path in /etc/sudoers - use sudo visudo to edit this file so that you get the benefit of a syntax check before you change the file.

Chris Davies
  • 116,213
  • 16
  • 160
  • 287
-1

Read man sudo sudoers. sudo commands intentionally ignore the user's $PATH, to avoid an easy security breach.

waltinator
  • 4,865