Git是一個分散式版本控制系統,同時它也是一個強大的代碼管理工具。Git帶來的一個巨大優勢就是可以準確追蹤代碼修改歷史。查看文件修改內容是一個常見的需求,本文將會從多個方面介紹如何使用git查看文件修改內容。
一、初始的文件狀態
在開始介紹如何查看文件修改內容之前,我們需要先創建一個初始狀態的文件,並且將其提交到Git倉庫中。
mkdir git-demo && cd git-demo
echo "Hello, World!" > hello.txt
git init
git add hello.txt
git commit -m "Add hello.txt"
現在,我們有了一個Git倉庫,並且倉庫中有一個文件hello.txt。
二、查看本地未提交的修改
在本地修改了文件後,我們可以使用git diff命令查看本地未提交的修改。
echo "Hello, Git!" > hello.txt
git diff hello.txt
上述命令將會輸出:
diff --git a/hello.txt b/hello.txt
index e69de29..6f8b8bd 100644
--- a/hello.txt
+++ b/hello.txt
@@ -0,0 +1 @@
+Hello, Git!
diff命令的輸出非常詳細,下面是每個部分的說明:
- diff –git a/hello.txt b/hello.txt:表示文件改動前後的差別
- index e69de29..6f8b8bd 100644:表示文件改動前後的版本號
- — a/hello.txt:表示文件改動前的版本
- +++ b/hello.txt:表示文件改動後的版本
- @@ -0,0 +1 @@:表示增加/刪除的行號
- +Hello, Git!:表示變動的內容
三、查看已提交的修改
如果我們想要查看某一次提交之後的修改,可以使用git diff命令,並指定某一個提交的ID。
echo "Hello, Git and GitHub!" > hello.txt
git add hello.txt
git commit -m "Update hello.txt"
git log
上述命令將會輸出當前提交歷史:
commit 10283133288bd65c1a4152a84c6f0964a2f062d7 (HEAD -> master)
Author: You
Date: Wed Jun 30 22:00:00 2021 +0800
Update hello.txt
commit d21c5ed13980bf1d76ebf230caae34f309799596
Author: You
Date: Wed Jun 30 21:00:00 2021 +0800
Add hello.txt
接著,我們可以使用git diff命令查看某一次提交之後的修改。
git diff d21c5ed hello.txt
上述命令將會輸出:
diff --git a/hello.txt b/hello.txt
index 1944a54..2bf273b 100644
--- a/hello.txt
+++ b/hello.txt
@@ -1 +1 @@
-Hello, World!
+Hello, Git and GitHub!
與之前的git diff命令輸出相似,這裡也是展示了文件改動前後的差別、文件改動前後的版本號、文件改動前的版本、文件改動後的版本、增加/刪除的行號和變動的內容。
四、查看指定區間的修改
假設我們想要查看某個區間的修改,可以使用git diff命令,並指定兩個提交ID。
echo "Hello, Git and GitLab!" > hello.txt
git add hello.txt
git commit -m "Update hello.txt"
git log
上述命令將會輸出當前提交歷史:
commit 2ac8e025c17f2a60cdaf5bad1ba170b8e3213a35 (HEAD -> master)
Author: You
Date: Wed Jun 30 22:01:00 2021 +0800
Update hello.txt
commit 10283133288bd65c1a4152a84c6f0964a2f062d7
Author: You
Date: Wed Jun 30 22:00:00 2021 +0800
Update hello.txt
commit d21c5ed13980bf1d76ebf230caae34f309799596
Author: You
Date: Wed Jun 30 21:00:00 2021 +0800
Add hello.txt
接著,我們可以使用git diff命令查看某個區間的修改。
git diff d21c5ed 2ac8e025 hello.txt
上述命令將會輸出:
diff --git a/hello.txt b/hello.txt
index 2bf273b..888228e 100644
--- a/hello.txt
+++ b/hello.txt
@@ -1 +1 @@
-Hello, Git and GitHub!
+Hello, Git and GitLab!
這裡的輸出與git diff命令查看已提交的修改的輸出類似。
五、查看某一行的修改
如果我們想要查看某一行的修改,可以使用git blame命令查找引入每一行的提交和作者,並使用git show命令查看某一次提交中的修改。
git blame hello.txt
上述命令將會輸出某一行的修改歷史,例如:
00000000 (Unknown 2021-06-30 21:00:00 +0800 1) Hello, World!
10283133 (You 2021-06-30 22:00:00 +0800 2) Hello, Git and GitHub!
2ac8e025 (You 2021-06-30 22:01:00 +0800 3) Hello, Git and GitLab!
我們可以找到想要查看的行號對應的提交ID。
git show 10283133
上述命令將會輸出某一次提交中的所有變更。
六、總結
通過本文的介紹,我們了解了如何在不同場景下使用Git查看文件的修改內容。Git是一個非常強大的代碼管理工具,在使用Git的過程中,隨時了解代碼歷史的變化是非常必要的。希望這篇文章可以幫助大家更好地使用Git。
原創文章,作者:小藍,如若轉載,請註明出處:https://www.506064.com/zh-tw/n/239965.html