Is there a way to get the git root directory in one command?

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?


Solution 1:

Yes:

git rev-parse --show-toplevel

If you want to replicate the Mercurial command more directly, you can create an alias:

git config --global alias.root 'rev-parse --show-toplevel'

and now git root will function just as hg root.


Note: In a submodule this will display the root directory of the submodule and not the parent repository. If you are using Git >=2.13 or above, there is a way that submodules can show the superproject's root directory. If your git is older than that, see this other answer.

Solution 2:

Has --show-toplevel only recently been added to git rev-parse or why is nobody mentioning it?

From the git rev-parse man page:

   --show-toplevel
       Show the absolute path of the top-level directory.

Solution 3:

The man page for git-config (under Alias) says:

If the alias expansion is prefixed with an exclamation point, it will be treated as a shell command. [...] Note that shell commands will be executed from the top-level directory of a repository, which may not necessarily be the current directory.

So, on UNIX you can do:

git config --global --add alias.root '!pwd'

Solution 4:

How about "git rev-parse --git-dir" ?

F:\prog\git\test\copyMerge\dirWithConflicts>git rev-parse --git-dir
F:/prog/git/test/copyMerge/.git

The --git-dir option seems to work.

From git rev-parse manual page:

--git-dir

    Show $GIT_DIR if defined else show the path to the .git directory.

You can see it in action in this git setup-sh script.

If you are in a submodule folder, with Git >=2.13, use:

git rev-parse --show-superproject-working-tree

If you are using git rev-parse --show-toplevel, make sure it is with Git 2.25+ (Q1 2020).

Solution 5:

To write a simple answer here, so that we can use

git root

to do the job, simply configure your git by using

git config --global alias.root "rev-parse --show-toplevel"

and then you might want to add the following to your ~/.bashrc:

alias cdroot='cd $(git root)'

so that you can just use cdroot to go to the top of your repo.