我正在zsh中编写Git管理的一系列脚本。

如何检查当前目录是否是Git存储库?(当我不在Git repo时,我不想执行一堆命令并得到一堆致命的:不是Git存储库响应)。


当前回答

不确定是否有公开可访问/记录的方法来做到这一点(有一些内部git函数,你可以在git源代码中使用/滥用)

你可以这样做;

if ! git ls-files >& /dev/null; then
  echo "not in git"
fi

其他回答

使用 git rev-parse --git-dir

if git rev-parse --git-dir > /dev/null 2>&1; then
  : # This is a valid git repository (but the current working
    # directory may not be the top level.
    # Check the output of the git rev-parse command if you care)
else
  : # this is not a git repository
fi

编辑:git-rev-parse现在(从1.7.0开始)支持——show- topllevel,所以你可以测试"$(pwd)"= "$(git rev-parse——show-toplevel)"来确定当前目录是否是顶级目录。

你可以使用:

git rev-parse --is-inside-work-tree

这将打印'true'如果你在一个git回购工作树。

注意,如果你在git repo之外,它仍然返回输出到STDERR(并且不打印'false')。

这个答案是:https://stackoverflow.com/a/2044714/12983

或者你可以这样做:

inside_git_repo="$(git rev-parse --is-inside-work-tree 2>/dev/null)"

if [ "$inside_git_repo" ]; then
  echo "inside git repo"
else
  echo "not in git repo"
fi

不确定是否有公开可访问/记录的方法来做到这一点(有一些内部git函数,你可以在git源代码中使用/滥用)

你可以这样做;

if ! git ls-files >& /dev/null; then
  echo "not in git"
fi

从bash完成文件复制,下面是一种简单的方法

# Copyright (C) 2006,2007 Shawn O. Pearce <spearce@spearce.org>
# Conceptually based on gitcompletion (http://gitweb.hawaga.org.uk/).
# Distributed under the GNU General Public License, version 2.0.

if [ -d .git ]; then
  echo .git;
else
  git rev-parse --git-dir 2> /dev/null;
fi;

您可以将其包装在函数中,也可以在脚本中使用。

浓缩成适合bash和zsh的一行条件

[ -d .git ] && echo .git || git rev-parse --git-dir > /dev/null 2>&1