Jason Axelson
Jason Axelson

Reputation: 4665

Programmatically get path to git directory in bash (including submodules)

Is it possible to programmatically find the path to the .git directory including for submodules?

I'm trying to write a script that installs a git hook but I can't find a straightforward way to find the .git directory for the project. Ideally it should cover the following cases:

  1. In root directory of project
  2. In sub-directory of project
  3. In root directory of submodule within project
  4. In sub-directory of submodule within project

I could do all of this manually but I'd rather not parse the .git file of a submodule.

Edit: I'd be interested in a solution in python as well.

Upvotes: 7

Views: 820

Answers (2)

Brandon
Brandon

Reputation: 2427

git rev-parse --git-dir seems to be what you want. I just tested it with a submodule:

cd mymodule
git rev-parse --git-dir  # --> .git
git submodule add ssh://.../path/to/mysubmodule
cd mysubmodule
git rev-parse --git-dir  # --> /home/.../mymodule/.git/modules/mysubmodule

This surprised me, since there was a .git in mysubmodule, but it turned out to be a file, with the following contents:

gitdir: ../.git/modules/mysubmodule

Upvotes: 5

vonbrand
vonbrand

Reputation: 11791

This SO question uses git rev-parse --show-toplevel to find the top directory.

Upvotes: 2

Related Questions