268

zsh で Git 管理用の一連のスクリプトを作成しています。

現在のディレクトリが Git リポジトリかどうかを確認するにはどうすればよいですか? fatal: Not a git repository(Git リポジトリにいないときは、一連のコマンドを実行して多数の応答を取得したくありません)。

4

14 に答える 14

192

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;

これを関数でラップするか、スクリプトで使用できます。

bashzshに適した1行の条件に凝縮されます

[ -d .git ] && echo .git || git rev-parse --git-dir > /dev/null 2>&1
于 2010-02-01T21:57:38.103 に答える
60

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-toplevelできます。if test "$(pwd)" = "$(git rev-parse --show-toplevel)"

于 2010-02-02T15:48:04.480 に答える
33

または、次のようにすることもできます。

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
于 2016-06-29T01:25:17.263 に答える
8

これを行うための公にアクセス可能/文書化された方法があるかどうかは不明です (git ソース自体で使用/悪用できる内部 git 関数がいくつかあります)

次のようなことができます。

if ! git ls-files >& /dev/null; then
  echo "not in git"
fi
于 2010-02-01T21:59:06.947 に答える
7

別の解決策は、コマンドの終了コードを確認することです。

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

git リポジトリ フォルダーにいる場合、これは 1 を出力します。

于 2015-12-14T10:14:16.710 に答える
5

終了コードを使用しないのはなぜですか? 現在のディレクトリに git リポジトリが存在する場合、git branchコマンドgit tagは終了コード 0 を返します。それ以外の場合は、ゼロ以外の終了コードが返されます。このようにして、git リポジトリが存在するかどうかを判断できます。簡単に実行できます:

git tag > /dev/null 2>&1

利点: ポータブル。ベアリポジトリと非ベアリポジトリの両方、およびsh、zsh、およびbashで機能します。

説明

  1. git tag: リポジトリのタグを取得して、存在するかどうかを判断します。
  2. > /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
于 2019-08-03T16:34:37.853 に答える