我正在尝试编写一个shell脚本,该脚本需要能够找到当前目录的.git
文件夹,正确处理以下所有可能性:
.git
文件夹是.
或..
或../..
等等。.git
文件)$GIT_DIR
可能已设置。我有这个:
seemsToBeGitdir() {
# Nothing special about "config --local -l" here, it's just a git
# command that errors out if the `--git-dir` argument is wrong.
git --git-dir "$1" config --local -l >/dev/null 2>/dev/null
return $?
}
gitdir() {
local cursor relpath
if [ "$GIT_DIR" ]; then
echo "$GIT_DIR"
return 0
fi
cursor="$(pwd)"
while [ -e "$cursor" ] && ! seemsToBeGitdir "$cursor"; do
# Git won't traverse mountpoints looking for .git
if mountpoint -q "$cursor"; then
return 1
fi
# We might be in a submodule
if [ -f "$cursor/.git" ]; then
# If .git is a file, its syntax is "gitdir: " followed by a
# relative path.
relpath="$(awk '/^gitdir:/{print$2}' "$cursor/.git")"
# convert the relative path to an absolute path.
cursor="$(readlink -f "$cursor/$relpath")"
continue
fi
if seemsToBeGitdir "$cursor/.git"; then
echo "$cursor/.git"
return 0
fi
cursor="$(dirname "$cursor")"
done
echo "$cursor"
}
它有效,但似乎太复杂了 - 很明显,git本身在每次调用时都会进行这种计算。有没有办法让git告诉我.git
在哪里?
答案 0 :(得分:4)
使用git rev-parse
,其中包含专门用于此的选项:
git rev-parse --git-dir
另见:
git rev-parse --absolute-git-dir
(Git版本2.13.0中的新功能)和:
git rev-parse --show-toplevel
和
git rev-parse --show-cdup
(请注意,如果您已经位于存储库的顶层,则其输出为空)。查看您自己的文档,了解您的Git支持哪些选项;其中大部分都是自Git 1.7以来的。