Mercurial has a way of printing the root directory (that contains .hg) via
hg root
Is there something equivalent in git to get the directory that contains the .git directory?
Mercurial has a way of printing the root directory (that contains .hg) via
hg root
Is there something equivalent in git to get the directory that contains the .git directory?
Since Git 2.13.0, it supports a new option to show the path of the root project, which works even when being used from inside a submodule:
Short solutions that work with submodules, in hooks, and inside the
.git
directoryHere's the short answer that most will want:
This will work anywhere in a git working tree (including inside the
.git
directory), but assumes that repository directory(s) are called.git
(which is the default). With submodules, this will go to the root of the outermost containing repository.If you want to get to the root of the current submodule use:
To easily execute a command in your submodule root, under
[alias]
in your.gitconfig
, add:This allows you to easily do things like
git sh ag <string>
Robust solution that supports differently named or external
.git
or$GIT_DIR
directories.Note that
$GIT_DIR
may point somewhere external (and not be called.git
), hence the need for further checking.Put this in your
.bashrc
:Execute it by typing
git_root
(after restarting your shell:exec bash
)This shell alias works whether you are in a git subdir, or at the top level:
updated to use modern syntax instead of backticks:
Has
--show-toplevel
only recently been added togit rev-parse
or why is nobody mentioning it?From the
git rev-parse
man page: