差分を表示する

Gitリポジトリの変更点を確認する方法を学びましょう。

git diffとは?

git diffは、Gitリポジトリの変更を確認するためのコマンドです。

git diffを使うことで、現在のワーキングツリーと最新のコミットとの差分を表示できます。

git-practiceディレクトリのhello.txtファイルを編集してみましょう。
コマンドラインのリダイレクトを使って、ファイルに追記します。

Terminal window
echo "Hello, Git!" >> hello.txt

次に、git diffコマンドを実行して、変更点を確認します。

Terminal window
git diff

次のように表示されれば、変更点が確認できます。

Terminal window
diff --git a/hello.txt b/hello.txt
index 670a245..793bffa 100644
--- a/hello.txt
+++ b/hello.txt
@@ -1 +1,2 @@
Hello, Git!
+Hello, Git!

ステージングと差分の確認

先ほどはワーキングツリーの変更点を確認しましたが、ステージングエリアに追加した変更点も確認できます。
まず、変更をステージングエリアに追加します。

Terminal window
git add hello.txt

この状態でgit diffコマンドを実行すると、何も表示されません。

git diff --cachedコマンドを実行して、ステージングエリアの変更点を確認します。

Terminal window
git diff --cached

次のように表示されれば、ステージングエリアの変更点が確認できます。

Terminal window
diff --git a/hello.txt b/hello.txt
index 670a245..793bffa 100644
--- a/hello.txt
+++ b/hello.txt
@@ -1 +1,2 @@
Hello, Git!
+Hello, Git!