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

hg root

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


当前回答

要计算当前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本身,请使用:/

# 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别名都有效:

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

如果有人需要POSIX兼容的方式来做到这一点,而不需要git可执行文件:

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

如果你只是想把这个功能作为脚本的一部分,删除shebang,并把最后一行git_root_recurse_parent替换为:

git_root() {
    (git_root_recurse_parent)
}

要计算当前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-config的手册页(在Alias下)说:

如果别名展开以感叹号作为前缀,则它将被视为外壳 命令。[…注意shell 命令将从存储库的顶级目录执行,这可能不是 必须是当前目录。

在UNIX上,你可以这样做:

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