对于给定的 Git 存储库,如何找到其索引文件的路径?

Wal*_*han 0 git git-index

假设我正在 Git 存储库中运行脚本并希望直接访问索引文件。如何以也尊重例如工作树的方式获取索引文件的路径?

Wal*_*han 6

git rev-parse您可以与该选项一起使用--git-path。从手册页:

       --git-path <path>
           Resolve "$GIT_DIR/<path>" and takes other path relocation variables such as $GIT_OBJECT_DIRECTORY, $GIT_INDEX_FILE... into account. For
           example, if $GIT_OBJECT_DIRECTORY is set to /foo/bar then "git rev-parse --git-path objects/abc" returns /foo/bar/abc.
Run Code Online (Sandbox Code Playgroud)

要具体获取索引文件,可以这样写:

$ git rev-parse --git-path index
.git/index
Run Code Online (Sandbox Code Playgroud)

这也尊重工作树:

$ git -C /path/to/my-worktree rev-parse --git-path index
/path/to/main/repo/.git/worktrees/my-worktree/index
Run Code Online (Sandbox Code Playgroud)

并尊重环境变量,例如GIT_INDEX_FILE

$ GIT_INDEX_FILE=foo git -C /path/to/my-worktree rev-parse --git-path index
foo
Run Code Online (Sandbox Code Playgroud)

请注意,其他解决方案(例如手动计算.git目录和附加路径)可能由于缺乏对上述内容的处理而不起作用。