简体   繁体   English

有人可以解释cd shell命令的来源吗?

[英]Can someone explain the source of the `cd` shell command?

$ cat $(which cd)
#!/bin/sh
# $FreeBSD: src/usr.bin/alias/generic.sh,v 1.2 2005/10/24 22:32:19   cperciva Exp $
# This file is in the public domain.
builtin `echo ${0##*/} | tr \[:upper:] \[:lower:]` ${1+"$@"}

My interest lies in understanding who records the state change after calling cd. 我的兴趣在于了解谁在致电cd后记录状态变化。 Is it in a file? 它在文件中吗?

This is not the cd builtin, and it doesn't actually work, except to tell if a directory can be changed into, by failing with a nonzero exit status if it cannot. 不是 cd内置的,它实际上不起作用,除了告诉目录是否可以更改为目录(如果不能通过非零退出状态失败)之外。

Try it: 试试吧:

"$(which cd)" /

...will do nothing. ...什么都不做。


The actual cd builtin is part of your shell, written in C, and calls the chdir() syscall. 实际的cd内置程序是用C语言编写的外壳程序的一部分,并调用chdir() syscall。 This syscall updates your process's state -- tracked by the kernel -- to have a different working directory. 该系统调用将更新进程的状态(由内核跟踪)以具有不同的工作目录。


...so, what is that chunk of shell script doing? ......那么,什么 shell脚本的该块做什么? Let's break it down: 让我们分解一下:

builtin `echo ${0##*/} | tr \[:upper:] \[:lower:]` ${1+"$@"}

...first, we're echo ing the command itself (in a somewhat buggy fashion, due to the lack of quotes) into tr , and changing it to all lower-case, such that if it were being called via a hardlink named CD it would still map to the builtin named cd . ...首先,我们echo荷兰国际集团的命令本身(有点越野车的时尚,由于缺乏引号)到tr ,并将其更改为全小写,这样,如果它正在通过硬连接称为命名CD ,它将仍然映射到名为cd的内置文件。

...second, ${1+"$@"} is passing all arguments ( "$@" ) through, if there are any arguments ( ${foo+bar} expands to bar only if foo is defined). ...第二, 如果有任何参数( ${foo+bar}仅在定义了foo情况下扩展为bar ), ${1+"$@"}将传递所有参数( "$@" )。

Thus, we're calling the shell-builtin cd (which in turn calls the chdir() syscall), with arguments passed through. 因此,我们正在调用带有内置参数的shell内置cd (依次调用chdir() syscall)。 The reason this builtin has no effect other than determining success or failure is because it's running out-of-process from the executable that invoked it -- so it changes the working directory of the shell started by the #!/bin/sh shebang, but not of any process or shell above that in the tree. 此内置程序除了确定成功或失败之外没有其他作用的原因是,它正在从调用它的可执行文件中进行进程外操作-因此它将更改以#!/bin/sh shebang开头的shell的工作目录,而不是树上的任何进程或外壳。


So, what does a real cd builtin look like? 那么, 真正的 cd内置外观是什么样的? Since it's short and easy-to-read, let's look at the Busybox ash implementation. 由于它简短易懂,因此让我们看一下Busybox ash实现。

  • Here is the entry-point... 是入口点...
  • Here is the actual operation. 是实际操作。
  • Here is the manual for the syscall invoked by the actual operation. 是实际操作所调用的syscall手册。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM