Is there a way to get the git root directory in on

2018-12-31 18:42发布

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?

22条回答
长期被迫恋爱
2楼-- · 2018-12-31 18:55

git-extras

adds $ git root
see https://github.com/tj/git-extras/blob/master/Commands.md#git-root

$ pwd
.../very-deep-from-root-directory
$ cd `git root`
$ git add . && git commit

Availability of git-extras

查看更多
后来的你喜欢了谁
3楼-- · 2018-12-31 18:56

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.

查看更多
初与友歌
4楼-- · 2018-12-31 18:57
alias git-root='cd \`git rev-parse --git-dir\`; cd ..'

Everything else fails at some point either going to the home directory or just miserably failing. This is the quickest and shortest way to get back to the GIT_DIR.

查看更多
情到深处是孤独
5楼-- · 2018-12-31 18:57

Here is a script that I've written that handles both cases: 1) repository with a workspace, 2) bare repository.

https://gist.github.com/jdsumsion/6282953

git-root (executable file in your path):

#!/bin/bash
GIT_DIR=`git rev-parse --git-dir` &&
(
  if [ `basename $GIT_DIR` = ".git" ]; then
    # handle normal git repos (with a .git dir)
    cd $GIT_DIR/..
  else
    # handle bare git repos (the repo IS a xxx.git dir)
    cd $GIT_DIR
  fi
  pwd
)

Hopefully this is helpful.

查看更多
旧时光的记忆
6楼-- · 2018-12-31 18:58

Pre-Configured Shell Aliases in Shell Frameworks

If you use a shell framework, there might already be a shell alias available:

  • $ grt in oh-my-zsh (68k) (cd $(git rev-parse --show-toplevel || echo "."))
  • $ git-root in prezto (8.8k) (displays the path to the working tree root)
  • $ g.. zimfw (1k) (changes the current directory to the top level of the working tree.)
查看更多
不再属于我。
7楼-- · 2018-12-31 19:02

Just in case if you're feeding this path to the Git itself, use :/

# this adds the whole working tree from any directory in the repo
git add :/

# and is equal to
git add $(git rev-parse --show-toplevel)
查看更多
登录 后发表回答