在不知道绝对路径的情况下 cd 到父目录

cd to parent directory without knowing absolute path to it

我需要返回到 bash 脚本中的父目录。我知道该目录将在我当前的路径中,但不知道它有多远,因为脚本可能会让我进入 2 到 5 层的任何深度。该脚本是克隆的 git 存储库的一部分,因此我无法从用户的根目录开始,因为我不知道他们将其克隆到何处或将下降多少层。

假设我的文件结构如下所示:

User's dir structure
  repo
    foo
      bar
       baz
        a
       fizz
        b
        bang
          c

我需要回到 foo,但我不知道我是在 ab 还是 c,甚至bar

我目前的想法是 pwd 并剪切它,所以我只是 */foo/ 然后 cd 到那个,但这真的是最有效的方法吗?

设置一个变量为原始目录。

origdir=$(pwd)
# code that jumps around...
cd "$origdir"

您也可以使用目录堆栈。

pushd -n "$PWD"  # Store the current working directory on the stack
...
popd  # Return to the directory on top of the stack

如果您不需要在 pushdpopd 之间进行大量目录更改,这将特别有用,因为您可以简单地编写

pushd some/directory/path  # Puts current working dir on the stack, then cd's to the argument
...
popd

(即使有变化,仍然可以使用pushdpushd foo等同于pushd -n "$PWD"; cd foo。)

您可以像这样进入存储库的根目录:

cd "$(git rev-parse --show-toplevel)"

因此,要从存储库内的任何位置访问其根目录中的 foo 目录:

cd "$(git rev-parse --show-toplevel)/foo"

git-rev-parse documentation