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

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


当前回答

#检查git是否回购

if [ $(git rev-parse --is-inside-work-tree) = true ]; then
    echo "yes, is a git repo"
    git pull
else
    echo "no, is not a git repo"
    git clone url --depth 1
fi

其他回答

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

你可以这样做;

if ! git ls-files >& /dev/null; then
  echo "not in git"
fi
##Current branch
echo $(git branch --show-current 2> /dev/null && echo '')
echo $(git branch --show-current 2> /dev/null)

##OR
GIT_DIR=$(git rev-parse --git-dir 2> /dev/null)

从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

另一个解决方案是检查命令的退出码。

git rev-parse 2> /dev/null; [ $? == 0 ] && echo 1

如果你在git存储库文件夹中,这将打印1。

你可以使用:

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

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

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

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