我正在zsh中编写Git管理的一系列脚本。
如何检查当前目录是否是Git存储库?(当我不在Git repo时,我不想执行一堆命令并得到一堆致命的:不是Git存储库响应)。
我正在zsh中编写Git管理的一系列脚本。
如何检查当前目录是否是Git存储库?(当我不在Git repo时,我不想执行一堆命令并得到一堆致命的:不是Git存储库响应)。
当前回答
##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)
其他回答
使用 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存储库,则git分支和git标记命令返回退出码为0;否则,将返回非零退出代码。通过这种方式,您可以确定git存储库是否存在。简单地说,你可以运行:
git tag > /dev/null 2>&1
优点:便于携带。它既适用于裸库,也适用于非裸库,以及在sh、zsh和bash中。
解释
git标签:获取存储库的标签,以确定是否存在。 > /dev/null 2>&1:阻止打印任何东西,包括正常和错误输出。
TLDR(真的吗?!):check-git-repo
例如,你可以创建一个名为check-git-repo的文件,包含以下内容,使其可执行并运行:
#!/bin/sh
if git tag > /dev/null 2>&1; then
echo "Repository exists!";
else
echo "No repository here.";
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。