在 Git 中比較檔案、提交和分支

John Wachira 2022年6月15日
在 Git 中比較檔案、提交和分支

本文將教我們如何使用 git diff 命令比較 Git 中的檔案、提交和分支。我們使用 git diff 命令來顯示由兩次提交或我們的 repo 的當前狀態和以前的提交產生的​​檔案之間的差異。

該命令在比較資料來源時派上用場。

git diff 命令

語法:

git diff

預設情況下,該命令將顯示我們倉庫中未提交的更改。

該命令將向我們顯示原始檔案中所有已刪除和新增的程式碼行。讓我們看看一些例子。

Git Diff 提交

我們可以在下面的上下文中比較同一分支中的兩個提交。

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 CorrectionSecond Code Correction 提交之間的差異的場景中,我們將如何處理呢?

我們將執行 git diff 命令並提及我們兩次提交的雜湊值,如下所示。

$ 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 行的差異。我們可以看到 Third Code Correction 提交刪除了 67 行的空程式碼行。

Git 差異分支

為了比較我們倉庫中的兩個分支,我們執行這個命令。

git diff <branch1> <branch2>

如果我們想比較 master 分支和另一個名為 dev.7 的分支,我們將執行此命令。

git diff master dev.7

如果我們在分支之間新增兩個點,Git 將比較兩者之間的最新提交。

Git 差異檔案

我們可以在下面的上下文中使用 git diff 命令比較我們倉庫中的兩個檔案。

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 命令中指定分支。如果檔案位於不同的分支中,則需要為每個檔案指定分支。

Author: John Wachira
John Wachira avatar John Wachira avatar

John is a Git and PowerShell geek. He uses his expertise in the version control system to help businesses manage their source code. According to him, Shell scripting is the number one choice for automating the management of systems.

LinkedIn

相關文章 - Git Diff