Git:git diff命令詳解,比較兩個版本的差異

最近更新時間 2020-01-01 21:46:30

git diff命令用於比較兩個版本之間的差異。

語法

git diff [<options>] [<commit>] [--] [<path>…​]
git diff [<options>] --cached [<commit>] [--] [<path>…​]
git diff [<options>] <commit> <commit> [--] [<path>…​]
git diff [<options>] <blob> <blob>
git diff [<options>] --no-index [--] <path> <path>

常用命令

1. 查看當前文件的差異。

git diff
效果同上,不顯示-a的內容
git diff HEAD
diff --git a/README.md b/README.md
index e845566..e965047 100644
--- a/README.md
+++ b/README.md
@@ -1 +1 @@
-README
+Hello

Note:如果是新加的文件,不會顯示任何信息,只比較修改的文件。

2. 顯示簡短信息。

git diff --stat
 main.c | 2 +-
 1 file changed, 1 insertion(+), 1 deletion(-)

3. 查看某個版本到當前版本的差異。

先使用git log --oneline -5命令查看提交的歷史記錄,獲取短哈希值,從下面信息查看顯示添加了一個文件。

git log --oneline -5
4d83e02 note
04f275c 2
git diff 04f275c 4d83e02
diff --git a/main.c b/main.c
new file mode 100644
index 0000000..ba2906d
--- /dev/null
+++ b/main.c
@@ -0,0 +1 @@
+main

4. 查看兩個分支的差異。

git diff branch1 branch2

5. 只顯示有差異文件的文件名。

git diff --name-only

6. 打包兩個版本增量文件。

git diff 0a03487 4d83e02 --name-only | xargs zip docsxyz.zip
  adding: README.md (stored 0%)
  adding: main.c (stored 0%)

7. 比較暫存區和某個版本的差異。

git diff --cached 0a03487
diff --git a/README.md b/README.md
index e845566..e965047 100644
--- a/README.md
+++ b/README.md
@@ -1 +1 @@
-README
+Hello
diff --git a/main.c b/main.c
new file mode 100644
index 0000000..ba2906d
--- /dev/null
+++ b/main.c
@@ -0,0 +1 @@
+main
rss_feed