我正在zsh中编写Git管理的一系列脚本。
如何检查当前目录是否是Git存储库?(当我不在Git repo时,我不想执行一堆命令并得到一堆致命的:不是Git存储库响应)。
我正在zsh中编写Git管理的一系列脚本。
如何检查当前目录是否是Git存储库?(当我不在Git repo时,我不想执行一堆命令并得到一堆致命的:不是Git存储库响应)。
当前回答
这个回答提供了一个示例POSIX shell函数和一个使用示例来补充@jabbie的回答。
is_inside_git_repo() {
git rev-parse --is-inside-work-tree >/dev/null 2>&1
}
如果它在Git存储库中,Git将返回errorlevel 0,否则将返回errorlevel 128。(如果它在git存储库中,它也会返回true或false。)
使用的例子
for repo in *; do
# skip files
[ -d "$repo" ] || continue
# run commands in subshell so each loop starts in the current dir
(
cd "$repo"
# skip plain directories
is_inside_git_repo || continue
printf '== %s ==\n' "$repo"
git remote update --prune 'origin' # example command
# other commands here
)
done
其他回答
##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
这个回答提供了一个示例POSIX shell函数和一个使用示例来补充@jabbie的回答。
is_inside_git_repo() {
git rev-parse --is-inside-work-tree >/dev/null 2>&1
}
如果它在Git存储库中,Git将返回errorlevel 0,否则将返回errorlevel 128。(如果它在git存储库中,它也会返回true或false。)
使用的例子
for repo in *; do
# skip files
[ -d "$repo" ] || continue
# run commands in subshell so each loop starts in the current dir
(
cd "$repo"
# skip plain directories
is_inside_git_repo || continue
printf '== %s ==\n' "$repo"
git remote update --prune 'origin' # example command
# other commands here
)
done
这对我很有用。您仍然会得到错误,但它们很容易被抑制。它也可以在子文件夹中工作!
git status >/dev/null 2>&1 && echo Hello World!
如果需要有条件地执行更多操作,可以将其放入if then语句中。
不确定是否有公开可访问/记录的方法来做到这一点(有一些内部git函数,你可以在git源代码中使用/滥用)
你可以这样做;
if ! git ls-files >& /dev/null; then
echo "not in git"
fi