为什么 sudo cd 会报错 command not found

某群有人提到在 Debian 下:

sudo cd xxx/

 会提示 sudo: cd: command not found (当然我大 Mac 是直接没有任何效果)

经查 OS X 的 man 手册写道:

It is not meaningful to run the cd command directly via sudo, e.g.

$ sudo cd /usr/local/protected

since when the command exits the parent process (your shell) will still be the same.  Please see the EXAMPLES section for more information.

实际上 ,执行一个外部程序时,shell 会 fork 一个子进程进行执行,而 cd 不是一个外部程序而是 shell 内建命令,因此 sudo 并不能找到一个叫做 cd 的外部程序执行,也不能作为子进程被执行(子进程不能影响其 shell 的工作目录),因此报 command not found ,类似的情况还有重定向等。

如果你使用

 sudo -i cd xxx/ && touch test

 会发现 xxx 目录下确实生成了一个 test 文件,这是因为 sudo -i 命令实际上是启动了一个新的 shell 执行了 cd 然后立刻退出,有点像

bash -c command

那么应该怎么达到这个目的呢?可以

sudo -s

 打开一个新的交互 shell 再执行 cd。

关于 sudo 和 su、交互式 shell 和命令执行有些有意思的讨论,参见下面的参考链接。

参考:

http://www.sudo.ws/pipermail/sudo-workers/2002-August/000145.html

http://forums.fedoraforum.org/archive/index.php/t-293897.html

 


本文链接:https://www.starduster.me/2015/09/12/why-command-not-found-when-sudo-cd/
本站基于 Creactive Commons BY-NC-SA 4.0 License 允许并欢迎您在注明来源和非商业使用前提下自由地对本文进行复制、分享或基于本文进行创作。
请注意:受限于笔者水平,本站内容可能存在主观臆断或事实错误,文中信息也可能因时间推移而不再准确,在此提醒读者结合自身判断谨慎地采纳。

发表回复

您的电子邮箱地址不会被公开。 必填项已用 * 标注

此站点使用Akismet来减少垃圾评论。了解我们如何处理您的评论数据