删除您所在的目录时 bash 的行为

fed*_*qui 6 bash

我正在使用GNU bash, version 4.3.42(1)-release (x86_64-redhat-linux-gnu).

我创建了一个虚拟目录hello并搬到了那里。进入后/tmp/hello,我删除了目录本身。

$ pwd
/tmp/hello
$ rmdir $PWD
Run Code Online (Sandbox Code Playgroud)

我检查了一下,我还在那个目录中。

$ pwd
/tmp/hello
Run Code Online (Sandbox Code Playgroud)

然后我尝试移动到目录本身,当然这是不可能的(即使我已经在那里):

$ cd $PWD
bash: cd: /tmp/hello: No such file or directory
Run Code Online (Sandbox Code Playgroud)

但是后来我尝试了cd .,因为它应该与cd $PWD. 这工作......不知何故:

$ cd .
cd: error retrieving current directory: getcwd: cannot access parent directories: No such file or directory
Run Code Online (Sandbox Code Playgroud)

令我惊讶的是,现在我处于一个新的“东西”中:

$ pwd
/tmp/hello/.
Run Code Online (Sandbox Code Playgroud)

如果我尝试转到上一个目录,它当然会失败:

$ cd -
bash: cd: /tmp/hello: No such file or directory
Run Code Online (Sandbox Code Playgroud)

有趣的是,man在那里甚至一个页面都不起作用:

$ man cd
man: can't change directory to '': No such file or directory
man: command exited with status 255: (cd  && LESS=-ix8RmPm Manual page cd(1) ?ltline %lt?L/%L.:byte %bB?s/%s..?e (END):?pB %pB\%.. (press h for help or q to quit)$PM Manual page cd(1) ?ltline %lt?L/%L.:byte %bB?s/%s..?e (END):?pB %pB\%.. (press h for help or q to quit)$ MAN_PN=cd(1) less -s)
Run Code Online (Sandbox Code Playgroud)

为什么会发生这一切?

sch*_*ily 1

POSIX要求缓存当前目录路径,并且删除的目录仍然存在但没有名称。

cd .显然只是将该字符串添加到当前缓存的名称中。