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

前端 未结 22 1288
被撕碎了的回忆
被撕碎了的回忆 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:48

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

    git-root:

    #$1: Path to child directory
    git_root_recurse_parent() {
        # Check if cwd is a git root directory
        if [ -d .git/objects -a -d .git/refs -a -f .git/HEAD ] ; then
            pwd
            return 0
        fi
    
        # Check if recursion should end (typically if cwd is /)
        if [ "${1}" = "$(pwd)" ] ; then
            return 1
        fi
    
        # Check parent directory in the same way
        local cwd=$(pwd)
        cd ..
        git_root_recurse_parent "${cwd}"
    }
    
    git_root_recurse_parent
    

    If you just want the functionality as part of a script, remove the shebang, and replace the last git_root_recurse_parent line with:

    git_root() {
        (git_root_recurse_parent)
    }
    

提交回复
热议问题