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

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.

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'

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).


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.