zsh で Git 管理用の一連のスクリプトを作成しています。
現在のディレクトリが Git リポジトリかどうかを確認するにはどうすればよいですか? fatal: Not a git repository
(Git リポジトリにいないときは、一連のコマンドを実行して多数の応答を取得したくありません)。
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に適した1行の条件に凝縮されます
[ -d .git ] && echo .git || git rev-parse --git-dir > /dev/null 2>&1
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)"
または、次のようにすることもできます。
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
これを行うための公にアクセス可能/文書化された方法があるかどうかは不明です (git ソース自体で使用/悪用できる内部 git 関数がいくつかあります)
次のようなことができます。
if ! git ls-files >& /dev/null; then
echo "not in git"
fi
別の解決策は、コマンドの終了コードを確認することです。
git rev-parse 2> /dev/null; [ $? == 0 ] && echo 1
git リポジトリ フォルダーにいる場合、これは 1 を出力します。
終了コードを使用しないのはなぜですか? 現在のディレクトリに git リポジトリが存在する場合、git branch
コマンドgit tag
は終了コード 0 を返します。それ以外の場合は、ゼロ以外の終了コードが返されます。このようにして、git リポジトリが存在するかどうかを判断できます。簡単に実行できます:
git tag > /dev/null 2>&1
利点: ポータブル。ベアリポジトリと非ベアリポジトリの両方、およびsh、zsh、およびbashで機能します。
git tag
: リポジトリのタグを取得して、存在するかどうかを判断します。> /dev/null 2>&1
: 正常出力とエラー出力を含め、何も印刷しないようにします。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