bash common sense issues

| 标签 tips 

今天遇到一个经验上的一个陷阱,蛮有意思的.
小伙伴问我为什么sudo前后的pip位置不一样?

[guohao@localhost ~]$ sudo type pip
pip is /bin/pip
[guohao@localhost ~]$ type pip
pip is /usr/bin/pip
[guohao@localhost ~]$ echo $PATH
/usr/local/bin:/usr/bin:/usr/local/sbin:/usr/sbin:/home/guohao/.local/bin:/home/guohao/bin
[guohao@localhost ~]$ sudo echo $PATH
/usr/local/bin:/usr/bin:/usr/local/sbin:/usr/sbin:/home/guohao/.local/bin:/home/guohao/bin

经验之谈就是sudo使用了root的PATH环境变量,然后echo一下path变量完全一致。

case 1:

[guohao@localhost ~]$ sudo bash
[root@localhost guohao]# type pip
pip is /bin/pip
[root@localhost guohao]# exit
[guohao@localhost ~]$ type pip
pip is /usr/bin/pip

发现case 1与之前的显示结果一致,type符合预期行为,从第一个PATH中打印pip的位置。这就很奇怪了,为什么切换到shell里面去和在外面的值不一致呢?

case2:

[guohao@localhost ~]$ echo 'echo $PATH' | sh
/usr/local/bin:/usr/bin:/usr/local/sbin:/usr/sbin:/home/guohao/.local/bin:/home/guohao/bin
[guohao@localhost ~]$ echo 'echo $PATH' | sudo sh
/sbin:/bin:/usr/sbin:/usr/bin

诡异了只有echo不一样!难道是sudo的特别复杂的特性,然后strace一下发现是bash的导致我犯了一个思维定势的错误。

[guohao@localhost ~]$ strace sudo echo "$PATH"
execve("/usr/bin/sudo", ["sudo", "echo", "/usr/local/bin:/usr/bin:/usr/loc"...], 0x7ffcccc6e8f0 /* 17 vars */) = 0

顺便赞扬一下strace的便利与强大。


PREV     NEXT