Hello. I’m trying to understand how sudo works, but I am having trouble understanding some details.
As I understand it when I run “sudo <command>”, the command is basically executed with a whitewashed version of my environment variables (including $PATH), but with root permissions. That also seems to be how it works. For example, I don’t have /sbin in my $PATH, so executing sudo ifconfig (ifconfig being located in /sbin/ifconfig) gives me:
$ sudo ifconfig
sudo: ifconfig: command not found
This I understand and is no problem. The proper way to do this is like so:
$ sudo -i ifconfig
eth0 [lots of output]
My confusion basically comes from what happens when I try inspecting what the $PATH actually is when running sudo. For example my path is:
$ env | grep ^PATH=
PATH=/usr/lib64/mpi/gcc/openmpi/bin:/home/qbd/bin:/usr/local/bin:/usr/bin:/bin:/usr/bin/X11:/usr/X11R6/bin:/usr/games:/usr/lib64/jvm/jre/bin
And with sudo I get:
$ sudo env | grep ^PATH=
PATH=/usr/sbin:/bin:/usr/bin:/sbin
Also I can try looking for ifconfig using which. Without sudo, which (correctly) does not find it:
which ifconfig
which: no ifconfig in (/usr/lib64/mpi/gcc/openmpi/bin:/home/qbd/bin:/usr/local/bin:/usr/bin:/bin:/usr/bin/X11:/usr/X11R6/bin:/usr/games:/usr/lib64/jvm/jre/bin)
But with sudo which indicates that ifconfig can be found:
$ sudo which ifconfig
/sbin/ifconfig
But recall that ifconfig won’t actually be found using just sudo.
So basically my question is why env and which seem to indicate that the path includes /sbin when running sudo, but in actuality it does not (sudo correctly inherits my $PATH as far as I can tell). Is there a good explanation for this behaviour?