LoginSignup
25

More than 5 years have passed since last update.

Gitディレクトリ外からgitコマンドを実行する

Last updated at Posted at 2018-01-18

スクリプトなどでgitコマンドを実行する際、わざわざリポジトリルートにcdするのが野暮ったいので辞めたい。

方法

1. コマンドラインオプションを利用する

Git 1.8.5以降ならこっち
$ git -C /path/to/repo [command]

Git 1.8.5未満ならこっち
$ git --git-dir=/path/to/repo/.git --work-tree=/path/to/repo [command]

Git 1.8.5以降であれば-Cオプション一発、1.8.5未満ならgit-dir, work-treeのオプション指定でいけるらしい
参考:work tree の外から git pull する

2. 環境変数を利用する

$ GIT_DIR=/path/to/repo/.git GIT_WORK_TREE=/path/to/repo git [command]

参考:Gitの内側 - 環境変数

GIT_DIR は .git フォルダの場所です。 指定されていない場合、Gitはディレクトリツリーを ~ または / にたどり着くまで上っていき、各ディレクトリで .git ディレクトリを探します。

GIT_WORK_TREE は、ベアリポジトリ以外のリポジトリで、ワーキングディレクトリのルートとなる場所です。 指定されていない場合、 $GIT_DIR の親ディレクトリが代わりに使用されます。

どっちがいいの?

正直どっちでもいいと思う。
単純にコマンド1発叩くだけならオプションの方がスマートに感じる。
複数のスクリプトを組み合わせる場合や、スクリプト外部からGitディレクトリを制御する場合は環境変数が良いのだろうなー。

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
25