HOWTO · Git
Git のファイル、コミット、ブランチを比較する
git diff コマンドを使用して、ファイルとコミットを比較できます。
このページの内容
この記事では、git diff コマンドを使用して Git のファイル、コミット、およびブランチを比較する方法を説明します。git diff コマンドを使用して、2つのコミット、またはリポジトリの現在の状態と前のコミットの結果として生じたファイル間の差異を表示します。
このコマンドは、データソースを比較するときに便利です。
git diff コマンド
構文:
git diff
デフォルトでは、コマンドはリポジトリ内のコミットされていない変更を表示します。
このコマンドは、元のファイルで削除および追加されたすべてのコード行を表示します。いくつかの例を見てみましょう。
Git Diff コミット
以下のコンテキストで、同じブランチ内の 2つのコミットを比較できます。
git diff <commit-1-id> <commit-2-id>
例:
これがローカルリポジトリのコミット履歴です。
$ git log --oneline
c84e6f9 (HEAD -> main) Third Code Correction
9af4e38 Second Code Correction
a45ca97 First Code Correction
8c1cefc My Commit Message
c5bf6c8 Sixth Commit
3b641e0 Fourth Commit
21ca1e7 Third Commit
b2f7710 Initial commit
Third Code Correction と Second Code Correction のコミットの違いを確認したいシナリオでは、どのように対処しますか?
以下に示すように、git diff コマンドを実行し、2つのコミットのハッシュについて言及します。
$ git diff 9af4e38 c84e6f9
diff --git a/insert.php b/insert.php
index 985a7af..a5f31c6 100644
--- a/insert.php
+++ b/insert.php
@@ -1,7 +1,6 @@
<?php
// Use ls command to shell_exec function
$output = shell_exec('git');
-
// Display the list of all files and directories
echo "<pre>$output</pre>";
?>
上記の出力は、行 67 での違いを示しています。3 番目のコード修正コミットにより、67 行の空のコード行が削除されたことがわかります。
Git Diff Branches
リポジトリ内の 2つのブランチを比較するには、このコマンドを実行します。
git diff <branch1> <branch2>
master ブランチと dev.7 という別のブランチを比較する場合は、このコマンドを実行します。
git diff master dev.7
ブランチ間に 2つのドットを追加すると、Git は 2つの間の最新のコミットを比較します。
Git Diff ファイル
以下のコンテキストで git diff コマンドを使用して、リポジトリ内の 2つのファイルを比較できます。
git diff <path-to-file1> <path-to-file2>
例:
$ git diff Head:sample.php HEAD:insert.php
diff --git a/sample.php b/insert.php
index dce9c57..a5f31c6 100644
--- a/sample.php
+++ b/insert.php
@@ -1,14 +1,6 @@
<?php
- $a= 23;
- $nationality = "Dutch";
- //applying conditions on nationality and age
- if ($nationality == "Dutch")
- {
- if ($a >= 18) {
- echo "Eligible to vote";
- }
- else {
- echo "Not eligible to vote";
- }
- }
+// Use ls command to shell_exec function
+$output = shell_exec('git');
+// Display the list of all files and directories
+echo "<pre>$output</pre>";
git diff コマンドでブランチを指定した方法に注意してください。ファイルが異なるブランチにある場合は、ファイルごとにブランチを指定する必要があります。