【linux】关于Linux shell中的cd和pwd对于simbolic link的行为

今天看《Unix环境高级编程》讲到getcwd()函数,提到取的是真实路径。试验了下shell下的cd 和 pwd

$cd /var
$ll mail
lrwxrwxrwx. 1 root root 10 Dec 19 03:12 mail -> spool/mail      # mail 是 spool/mail的软链接
$cd mail
$pwd
/var/mail
$pwd -P
/var/spool/mail
$cd ..         
$pwd -P
/var                    #从 /var/mail 执行 cd .. 命令 返回到/var目录
$cd /var/spool/mail
$cd ..
$pwd -P
/var/spool              #从 /var/spool/mail 执行 cd .. 命令 返回到/var/spool目录

从apue前面章节可以知道,simbolic link 是个文件, 该文件的实际内容(在数据块中)包含了该符号链接所指向的文件的名字。这样,我们执行"cd mail"命令时,实际上要找寻到 /var/spool/mail 所对应的 inode,所以实际上 cd /var/mail 和 cd /var/spool/mail 均能到达同一个目录。这样问题就来了,既然是同一个目录,那目录项中的".." 对应的inode也应该一样,那为什么 "cd .." 会进入到不同的父目录呢?

谷歌了下,查到这么个解释:

 Shells nowadays keep track of how they got where they are, they keep track of current working directory by name, rather than just relying on file system and OS to keep it. That means the built-in cd can go "back up" the symbolic link, rather than just following ".." chains directly.

上述解释来自StackExchange的symbolic link to a directory and relative path

另外apue提到当前工作目录是进程的一个属性,所以它只影响调用chdir的进程本身,而不影响其他进程,所以这也是cd和pwd命令会是 built-in的原因。

谷歌到的回答中有一种解释提到 "cd .." 是用到了 shell的环境变量 $PWD (或$OLDPWD),感觉很对,但是试验了下,发现却不是这么回事

$pwd
/var/mail
$PWD=/home/root
$echo $PWD
/home/root
$OLDPWD=/home/root     #设置$PWD和$OLDPWD为/home/root
$cd ..                  
$pwd                   #cd .. 却还是回到/var
/var

百撕不得骑姐阿!于是去找了下 bash 的源码看了下……

查看 builtins/cd.def ,最终发现了这个全局变量——"the_current_working_directory"。原来shell将当前的工作目录(cd/pushd等的路径)保存了起来,而 $PWD和$OLDPWD只不过是执行cd 命令后 根据the_current_working_directory设置的。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值