Mercurial有一种打印根目录(包含.hg)的方法

hg root

git中是否有等价的东西来获取包含.git目录的目录?


当前回答

以防万一,如果您要将此路径提供给Git本身,请使用:/

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

其他回答

要计算当前git根目录的绝对路径,比如在shell脚本中使用,使用readlink和git rev-parse的组合:

gitroot=$(readlink -f ./$(git rev-parse --show-cdup))

Git-rev-parse——show-cdup给出正确的“..”’s to get 从你的cwd到根目录,如果你在根目录,则返回空字符串。 然后“prepend”。/"来处理空字符串大小写并使用 Readlink -f转换为完整路径。

你也可以在PATH中创建一个git-root命令作为shell脚本来应用这个技术:

cat > ~/bin/git-root << EOF
#!/bin/sh -e
cdup=$(git rev-parse --show-cdup)
exec readlink -f ./$cdup
EOF
chmod 755 ~/bin/git-root

(上面的代码可以粘贴到终端中创建git-root并设置执行位;实际的脚本在第2、3和4行。)

然后你可以运行git root来获得当前树的根。 注意,在shell脚本中,使用“-e”使shell在rev-parse失败时退出,这样如果不在git目录中,就可以正确地获得退出状态和错误消息。

“git rev-parse——git-dir”怎么样?

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

——git-dir选项似乎可以工作。

它甚至可以在裸库中工作,而git rev-parse——show- topllevel会触发(在裸库中)“致命:此操作必须在工作树中运行”。

从git rev-parse手册页:

--git-dir

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

您可以在这个git setup-sh脚本中看到它的作用。

如果你在子模块文件夹中,Git >=2.13,使用:

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

如果你正在使用git rev-parse——show-toplevel,请确保使用的是git 2.25+ (Q1 2020)。

不管你是在git子目录下,还是在顶层,这个shell别名都有效:

alias gr='[ ! -z `git rev-parse --show-toplevel` ] && cd `git rev-parse --show-toplevel || pwd`'

更新为使用现代语法而不是反撇号:

alias gr='[ ! -z $(git rev-parse --show-toplevel) ] && cd $(git rev-parse --show-toplevel || pwd)'

下面是我编写的处理这两种情况的脚本:1)带工作区的存储库,2)裸存储库。

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

Git-root(可执行文件在你的路径):

#!/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
)

希望这对你们有帮助。

修改一下“git配置”的答案:

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

把道路清理干净。很好。