gitの使い方メモ

gitの管理対象のファイルを作る。

myprojectディレクトリを作る。

$ mkdir myproject
$ cd myproject

「uhouho」という文字列が記述されたファイル「test.txt」を作る。

$ echo uhouho > test.txt

gitの初期設定

氏名とメールアドレスを設定する。

$ git config --global user.name "hato_mune"
$ git config --global user.email "hato_mune@gmail.com

リポジトリを作成する。

$ cd myproject
$ git init

このコマンドを実行すると可憐とディレクトリに「.git」というディレクトリが作成される。

gitの管理対象ファイル

gitの管理対象ファイルを"索引(index)"に追加

$ git add test.txt

コミットする。

$ git commit

上記のコマンドを打つと、viが開いてコメント入力が求められるので、
「Initial commit」などと入力して保存して終了する。
ここで最初のバージョンがコミットされる。
test.txtを変更して、コミット。

$ echo hogehoge >> test.txt

差分を確認する。

$ git diff
diff --git a/test.txt b/test.txt
index 99ebcc0..62a24b7 100644
--- a/test.txt
+++ b/test.txt
@@ -1 +1,2 @@
 uhouho
+hogehoge

変更したファイルを索引に追加。

$ git add test.txt

索引に登録されたけど、コミットされていないファイルを確認。

$ git diff --cached
diff --git a/test.txt b/test.txt
index 99ebcc0..62a24b7 100644
--- a/test.txt
+++ b/test.txt
@@ -1 +1,2 @@
 uhouho
+hogehoge

コミットする。

$ git commit

test2.txtを新規作成、コミット

test2.txtを作成

$ echo ohyoohyo > test2.txt

test2.txtを索引に追加し、コミット

$ git add test2.txt
$ git commit

test2.txtを変更し、コミット

$ echo ahyaahay >> test2.txt

索引して、コミットするのは次の一行で書ける。

$ git commit -a

ブランチ管理

"experimental"というブランチを作成する。

$ git branch experimental

ブランチ一覧を表示

$ git branch
  experimental
* master

上記は、"experimental"と"master"というブランチがあることを示している。
「*」は、現在のブランチを指し示している。
作業ブランチを"experimental"に切り替える。

$ git checkout experimental
Switched to branch "experimental"
$ git branch
* experimental
  master

"experimental"上で、test.txtの内容を変更して、コミットする。

$ echo experimental > test.txt
$ git commit -a

作業ブランチを"master"に切り替えて、test2.txtの内容を変更する。

$ git checkout master
Switched to branch "master"
$ echo master > test2.txt
$ git commit -a

この時点で、下記のような状況となっている。

  • "experimental"上で、test.txtの内容が「experimental」となっている。
  • "master"上で、test2.txtの内容が「master」となっている。

これらの変更を"master"上でマージする。

$ git merge experimental
$ cat test.txt
experimental
$ cat test2.txt
master

マージした結果は、GUIツールで確認できる。

gitk