對於已經修改的文件,你可能想查看具體修改了哪些內容。可以用 git diff
命令。
git diff 是比較同一個文件不同狀態之間做了哪些修改。可以理解為同一個文件的兩個副本之間做了哪些修改。
那是哪兩個副本之間比較的呢?
一、查看已暫存和未暫存的修改
1. 查看未暫存的修改。
此時比較的是 已暫存(staged)和 已追蹤未暫存(modified) 之間的修改部分。
此時執行 git status 查看文件狀態:
$ git status
On branch master
No commits yet
Changes to be committed:
(use "git rm --cached <file>..." to unstage)
new file: .gitignore
Untracked files:
(use "git add <file>..." to include in what will be committed)
hello.txt
提示 hello.txt未追蹤。再執行git diff命令:
$ git diff
輸出為空,表示當前已暫存文件和已修改文件沒有區別。因為當前就沒有modified狀態的文件啊。
此時我們追蹤 hello.txt ,執行命令 git add hello.txt ,並查看狀態:
$ git add hello.txt
$ git status
On branch master
No commits yet
Changes to be committed:
(use "git rm --cached <file>..." to unstage)
new file: .gitignore
new file: hello.txt
$ git diff
此時hello.txt已追蹤,我們修改 hello.txt 的內容,第一行輸入hello,保存。並執行 git diff。【注意此時 hello.txt 中已經有一行內容了,內容為hello world,我們將其改為了hello】
$ git status
On branch master
No commits yet
Changes to be committed:
(use "git rm --cached <file>..." to unstage)
new file: .gitignore
new file: hello.txt
Changes not staged for commit:
(use "git add <file>..." to update what will be committed)
(use "git restore <file>..." to discard changes in working directory)
modified: hello.txt
$ git diff
diff --git a/hello.txt b/hello.txt
index 95d09f2..b6fc4c6 100644
--- a/hello.txt
+++ b/hello.txt
@@ -1 +1 @@
-hello world
\ No newline at end of file
+hello
\ No newline at end of file
a/hello.txt是已暫存文件,b/hello.txt 是工作區的文件
顯示,已暫存文件內容是 hello world,工作區文件內容是hello。這里修改了。
執行 git add hello.txt 將修改暫存。再次查看狀態和文件內容。
$ git add hello.txt
$ git status
On branch master
No commits yet
Changes to be committed:
(use "git rm --cached <file>..." to unstage)
new file: .gitignore
new file: hello.txt
此時 hello.txt的文件內容為hello。
2. 查看已暫存修改
git diff --cached 命令
此時比較的是 提交至倉庫的版本 和 暫存區文件 之間的修改部分。
到現在為止,我們還沒有提交過版本。執行 git diff --cache
$ git diff --cached
diff --git a/.gitignore b/.gitignore
new file mode 100644
index 0000000..e69de29
diff --git a/hello.txt b/hello.txt
new file mode 100644
index 0000000..b6fc4c6
此時比較內容為空,因為倉庫里沒有版本,我們還未提交過。現在我們提交項目的第一個版本。
提交版本的命令是 git commit -m <message> message是此次提交的備注,是必填項。
執行 git commit -m 初次提交 命令
$ git commit -m 初次提交
[master (root-commit) 337070e] 初次提交
2 files changed, 1 insertion(+)
create mode 100644 .gitignore
create mode 100644 hello.txt
此時倉庫的有了版本,hello.txt 的內容為 hello。此時我們修改內容為 hi,保存,並暫存文件,再執行 git diff --cached 查看。
$ git add hello.txt
$ git diff --cached
diff --git a/hello.txt b/hello.txt
index b6fc4c6..32f95c0 100644
--- a/hello.txt
+++ b/hello.txt
@@ -1 +1 @@
-hello
\ No newline at end of file
+hi
\ No newline at end of file
此時顯示我們將 hello.txt 的內容由 hello 改為了 hi。
注意:--staged 和 --cached 是同義詞
git diff --cached 等於 git diff --staged
總結:
掌握git diff命令的重點在於,明白Git文件的四種狀態,以及文件的所在區域。
文件所在的區域有三個:工作區、暫存區、倉庫。
文件的流轉方向是由工作區創建,add進入暫存區,commit進入倉庫。
git diff的比較是從右向左。
git diff 比較暫存區與工作區文件的區別。
git diff --cached 比較倉庫與暫存區文件的區別。
轉載自:知優碼 https://www.javaidea.cn/topic/1237.html