Mercurial有一种打印根目录(包含.hg)的方法
hg root
git中是否有等价的东西来获取包含.git目录的目录?
Mercurial有一种打印根目录(包含.hg)的方法
hg root
git中是否有等价的东西来获取包含.git目录的目录?
当前回答
如果有人需要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)
}
其他回答
在Shell框架中预先配置的Shell别名
如果你使用shell框架,可能已经有一个可用的shell别名:
$ GRT in oh-my-zsh (68k) (cd $(git rev-parse——show-toplevel || echo ".")) $ git-root in prezto (8.8k)(显示工作树根的路径) $ g . .Zimfw (1k)(将当前目录更改为工作树的顶层。)
从Git 2.13.0开始,它支持一个新的选项来显示根项目的路径,即使在子模块内部使用也可以工作:
git rev-parse --show-superproject-working-tree
如果有人需要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)
}
alias git-root='cd \`git rev-parse --git-dir\`; cd ..'
其他所有东西都会在某一时刻失败要么是到主目录,要么就是悲惨地失败。这是返回GIT_DIR的最快和最短的方法。
修改一下“git配置”的答案:
git config --global --add alias.root '!pwd -P'
把道路清理干净。很好。