检查当前目录是否是 Git 存储库

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/2180270/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-10 07:46:31  来源:igfitidea点击:

Check if current directory is a Git repository

gitzsh

提问by anon

I am writing a series of scripts for Git management in zsh.

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

How do I check if the current directory is a Git repository? (When I'm not in a Git repo, I don't want to execute a bunch of commands and get a bunch of fatal: Not a git repositoryresponses).

如何检查当前目录是否是 Git 存储库?(当我不在 Git 存储库中时,我不想执行一堆命令并获得一堆fatal: Not a git repository响应)。

采纳答案by jabbie

Copied from the bash completion file, the following is a naive way to do it

复制自bash补全文件,下面是很幼稚的做法

# Copyright (C) 2006,2007 Shawn O. Pearce <[email protected]>
# 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;

You could either wrap that in a function or use it in a script.

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

Condensed into a one line condition suitable for bashand zsh

浓缩成适合bashzsh的单行条件

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

回答by TM.

You can use:

您可以使用:

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

Which will print 'true' if you are in a git repos working tree.

如果您在 git repos 工作树中,它将打印“true”。

Note that it still returns output to STDERR if you are outside of a git repo (and does not print 'false').

请注意,如果您在 git 存储库之外(并且不打印“false”),它仍会将输出返回给 STDERR。

Taken from this answer: https://stackoverflow.com/a/2044714/12983

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

回答by William Pursell

Use git rev-parse --git-dir

使用 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

回答by Alex Cory

Or you could do this:

或者你可以这样做:

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

回答by James

Not sure if there is a publicly accessible/documented way to do this (there are some internal git functions which you can use/abuse in the git source itself)

不确定是否有公开访问/记录的方法来执行此操作(有一些内部 git 函数您可以在 git 源本身中使用/滥用)

You could do something like;

你可以做类似的事情;

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

回答by ivan_pozdeev

Based on @Alex Cory's answer:

基于@Alex Cory 的回答

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

doesn't contain any redundant operations and works in -emode.

不包含任何冗余操作并在-e模式下工作。

  • As @go2null noted, this will not work in a bare repo. If you want to work with a bare repo for whatever reason, you can just check for git rev-parsesucceeding, ignoring its output.
    • I don't consider this a drawback because the above line is indended for scripting, and virtually all gitcommands are only valid inside a worktree. So for scripting purposes, you're most likely interested in being not just inside a "git repo" but inside a worktree.
  • 正如@go2null 指出的那样,这在裸仓库中不起作用。如果您出于任何原因想使用裸仓库,您可以只检查是否git rev-parse成功,而忽略其输出。
    • 我不认为这是一个缺点,因为上面的行是为脚本编写的,而且几乎所有git命令都只在工作树内有效。因此,出于编写脚本的目的,您很可能不仅对“git repo”感兴趣,而且对工作树感兴趣。

回答by ivan_pozdeev

Another solution is to check for the command's exit code.

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

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

This will print 1 if you're in a git repository folder.

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

回答by go2null

This answer provides a sample POSIX shell function and a usage example to complement @jabbie's answer.

这个答案提供了一个示例 POSIX shell 函数和一个使用示例来补充@jabbie 的答案

is_inside_git_repo() {
    git rev-parse --is-inside-work-tree >/dev/null 2>&1
}

gitreturns errorlevel 0if it is inside a git repository, else it returns errorlevel 128. (It also returns trueor falseif it is inside a git repository.)

git返回ERRORLEVEL0如果它是一个Git仓库里面,否则返回错误级别128。(它也会返回,true或者false它是否在 git 存储库中。)

Usage example

使用示例

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

回答by CharlesTWall3

this works for me. You still get the errors but they're easy enough to suppress. it also works from within subfolders!

这对我有用。您仍然会遇到错误,但它们很容易抑制。它也适用于子文件夹内!

git status >/dev/null 2>&1&& echo Hello World!

git status >/dev/null 2>&1&& echo Hello World!

You can put this in an if then statement if you need to conditionally do more.

如果您需要有条件地执行更多操作,可以将其放入 if then 语句中。

回答by MAChitgarha

Why not using exit codes? If a git repository exists in the current directory, then git branchand git tagcommands return exit code of 0; otherwise, a non-zero exit code will be returned. This way, you can determine if a git repository exist or not. Simply, you can run:

为什么不使用退出代码?如果当前目录存在git仓库,则git branchgit tag命令返回退出码0;否则,将返回非零退出代码。通过这种方式,您可以确定 git 存储库是否存在。简单地说,你可以运行:

git tag > /dev/null 2>&1 && [ $? -eq 0 ]

Advantage: Flexibe. It works for both bare and non-bare repositories, and in sh, zsh and bash.

优点:灵活。它适用于裸和非裸存储库,以及 sh、zsh 和 bash。

Explanation

解释

  1. git tag: Getting tags of the repository to determine if exists or not.
  2. > /dev/null 2>&1: Preventing from printing anything, including normal and error outputs.
  3. [ $? -eq 0 ]: Check if the previous command returned with exit code 0 or not. As you may know, every non-zero exit means something bad happened. $?gets the exit code of the previous command, and [, -eqand ]perform the comparison.
  1. git tag:获取存储库的标签以确定是否存在。
  2. > /dev/null 2>&1:防止打印任何内容,包括正常和错误输出。
  3. [ $? -eq 0 ]: 检查上一个命令是否返回退出代码 0。您可能知道,每个非零退出都意味着发生了不好的事情。$?获取上一条命令的退出码,和[-eq]进行比较。

As an example, you can create a file named check-git-repowith the following contents, make it executable and run it:

例如,您可以创建一个以check-git-repo以下内容命名的文件,使其可执行并运行它:

#!/bin/sh

if git tag > /dev/null 2>&1 && [ $? -eq 0 ]; then
    echo "Repository exists!";
else
    echo "No repository here.";
fi