尽管采购,但无法从 bash 脚本更改目录

Not able to change directory from bash script despite sourcing

我有以下 2 个文件:

文件 cd2vcaa(在路径中):

#! /bin/bash
cd /var/cache/apt/archives

文件test.sh(在当前目录):

#! /bin/bash
. cd2vcaa

从终端,我可以使用 . cd2vcaa 更改目录,但不能使用 ./test.sh

~$ cd2vcaa                        <-- no effect
~$ . cd2vcaa                      <-- changes directory
/var/cache/apt/archives$ cd       <-- back to home directory
~$ ./test.sh                      <-- does not change directory though no error - why?
~$

为什么 . cd2vcaa 是从终端工作,而是从另一个脚本中工作? 如何解决这个问题?

当您使用 ./test.sh 调用它时,test.sh 运行 位于单独的 shell 中,因此尽管 test.sh 中的采购意味着 cd 命令将影响 shell 中的当前目录,其中 test.sh 运行s,因此例如在 test.sh 末尾添加的任何命令将 运行 当前目录 /var/cache/apt/archives,不会影响父目录 shell(您的登录会话)。

如果您通过获取它 (. test.sh) 来调用 test.sh,那么在任一阶段都不会启动子 shell,并且目录会在您的登录会话中更改。

正如评论中所讨论的,如果目的只是为了使用交互式 shell,它被 cd-ed 到指定目录(不一定是父 shell ),那么一个选项就是将 bash 放在 test.sh 的末尾,以便在 cd 命令 运行 之后启动交互式子 shell ].从此子 shell 退出时,控件将 return 转到登录 shell,仍在其原始工作目录中。