有人可以解释cd shell命令的来源吗? [英] Can someone explain the source of the `cd` shell command?

查看:137
本文介绍了有人可以解释cd shell命令的来源吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

$ 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+"$@"}

我的兴趣在于了解谁在致电cd后记录状态变化.它在文件中吗?

My interest lies in understanding who records the state change after calling cd. Is it in a file?

推荐答案

这不是内置的cd不是,它实际上不起作用,只是告诉目录是否为可以通过变为非零退出状态(如果无法退出)来更改为它们.

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.

尝试一下:

"$(which cd)" /

...什么都不做.

实际的cd内置程序是用C编写的shell的一部分,并调用chdir() syscall.此系统调用将更新进程的状态(由内核跟踪)以具有不同的工作目录.

The actual cd builtin is part of your shell, written in C, and calls the chdir() syscall. This syscall updates your process's state -- tracked by the kernel -- to have a different working directory.

...那么,那段shell脚本在做什么 ?让我们分解一下:

...so, what is that chunk of shell script doing? Let's break it down:

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

...首先,我们将echo命令本身(由于缺少引号而以某种错误的方式)放入tr,并将其更改为所有小写字母,例如通过名为CD的硬链接被调用,它仍将映射到名为cd的内置文件.

...first, we're echoing 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.

...第二次,${1+"$@"}将所有参数("$@")传递给,如果有任何参数(仅在定义了foo的情况下,${foo+bar}扩展为bar ).

...second, ${1+"$@"} is passing all arguments ("$@") through, if there are any arguments (${foo+bar} expands to bar only if foo is defined).

因此,我们将调用shell-builtin cd(又称为chdir() syscall),并传递参数.该内置变量除了确定成功或失败之外没有其他作用的原因是,它正在从调用它的可执行文件中进行进程外操作-因此它将更改由#!/bin/sh shebang开始的shell的工作目录,但不能更改树中位于其上方的任何进程或外壳.

Thus, we're calling the shell-builtin cd (which in turn calls the chdir() syscall), with arguments passed through. 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.

那么,真实 cd内置的外观是什么样的?由于它简短易懂,因此让我们看一下Busybox ash的实现.

So, what does a real cd builtin look like? Since it's short and easy-to-read, let's look at the Busybox ash implementation.

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

这篇关于有人可以解释cd shell命令的来源吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆