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

前端 未结 22 1023
被撕碎了的回忆
被撕碎了的回忆 2020-11-22 09:57

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

相关标签:
22条回答
  • 2020-11-22 10:35

    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.

    0 讨论(0)
  • 2020-11-22 10:36

    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.

    0 讨论(0)
  • 2020-11-22 10:38

    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)'
    
    0 讨论(0)
  • 2020-11-22 10:40

    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.

    0 讨论(0)
  • 2020-11-22 10:42

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

    0 讨论(0)
  • 2020-11-22 10:43

    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)"'
    
    0 讨论(0)
提交回复
热议问题