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:43

In case anyone needs a POSIX compliant way of doing this, without needing git executable:

git-root:

#!/bin/sh

#$1: Path to child directory
recurse_parent() {

    if is_cwd_git_root ; then
        pwd
        return 0
    fi

    if [ "${1}" = "$(pwd)" ] ; then
        return 1
    fi

    cd ..
    recurse_parent "${CWD}"


}

is_cwd_git_root() {
    [ -d .git/objects -a -d .git/refs -a -f .git/HEAD ]
}

recurse_parent
查看更多
忆尘夕之涩
3楼-- · 2018-12-31 18:44

To calculate the absolute path of the current git root directory, say for use in a shell script, use this combination of readlink and git rev-parse:

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

git-rev-parse --show-cdup gives you the right number of ".."s to get to the root from your cwd, or the empty string if you are at the root. Then prepend "./" to deal with the empty string case and use readlink -f to translate to a full path.

You could also create a git-root command in your PATH as a shell script to apply this technique:

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

(The above can be pasted into a terminal to create git-root and set execute bits; the actual script is in lines 2, 3 and 4.)

And then you'd be able to run git root to get the root of your current tree. Note that in the shell script, use "-e" to cause the shell to exit if the rev-parse fails so that you can properly get the exit status and error message if you are not in a git directory.

查看更多
听够珍惜
4楼-- · 2018-12-31 18:45

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.20, use:

git rev-parse --show-superproject-working-tree
查看更多
刘海飞了
5楼-- · 2018-12-31 18:45

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.

查看更多
皆成旧梦
6楼-- · 2018-12-31 18:45
$ git config alias.root '!pwd'
# then you have:
$ git root
查看更多
心情的温度
7楼-- · 2018-12-31 18:46

Yes:

git rev-parse --show-toplevel
查看更多
登录 后发表回答