Mercurial has a way of printing the root directory (that contains .hg) via
hg root
Is there something equivalent in git to get the director
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.
To amend the "git config" answer just a bit:
git config --global --add alias.root '!pwd -P'
and get the path cleaned up. Very nice.
This shell alias works whether you are in a git subdir, or at the top level:
alias gr='[ ! -z `git rev-parse --show-toplevel` ] && cd `git rev-parse --show-toplevel || pwd`'
updated to use modern syntax instead of backticks:
alias gr='[ ! -z $(git rev-parse --show-toplevel) ] && cd $(git rev-parse --show-toplevel || pwd)'
Yes:
git rev-parse --show-toplevel
If you want to replicate the Git 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.
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).
If you're looking for a good alias to do this plus not blow up cd
if you aren't in a git dir:
alias ..g='git rev-parse && cd "$(git rev-parse --show-cdup)"'