## git diff 顯示已寫入緩存與已修改但尚未寫入緩存的改動的區別
`git diff`?有兩個主要的應用場景。我們將在此介紹其一, 在?[檢閱與對照](http://gitref.org/inspect)?一章中,我們將介紹其二。 我們這里介紹的方式是用此命令描述已臨時提交的或者已修改但尚未提交的改動。
### git diff?#尚未緩存的改動
如果沒有其他參數,`git diff`?會以規范化的 diff 格式(一個補丁)顯示自從你上次提交快照之后尚未緩存的所有更改。
~~~
$ vim hello.rb
$ git status -s
M hello.rb
$ git diff
diff --git a/hello.rb b/hello.rb
index d62ac43..8d15d50 100644
--- a/hello.rb
+++ b/hello.rb
@@ -1,7 +1,7 @@
class HelloWorld
def self.hello
- puts "hello world"
+ puts "hola mundo"
end
end
~~~
所以,`git status`顯示你上次提交更新至后所更改或者寫入緩存的改動, 而?`git diff`?一行一行地顯示這些改動具體是啥。 通常執行完?`git status`?之后接著跑一下?`git diff`?是個好習慣。
### git diff –cached?#查看已緩存的改動
`git diff --cached`?命令會告訴你有哪些內容已經寫入緩存了。 也就是說,此命令顯示的是接下來要寫入快照的內容。所以,如果你將上述示例中的?`hello.rb`?寫入緩存,因為?`git diff`顯示的是尚未緩存的改動,所以在此執行它不會顯示任何信息。
~~~
$ git status -s
M hello.rb
$ git add hello.rb
$ git status -s
M hello.rb
$ git diff
$
~~~
如果你想看看已緩存的改動,你需要執行的是?`git diff --cached`。
~~~
$ git status -s
M hello.rb
$ git diff
$
$ git diff --cached
diff --git a/hello.rb b/hello.rb
index d62ac43..8d15d50 100644
--- a/hello.rb
+++ b/hello.rb
@@ -1,7 +1,7 @@
class HelloWorld
def self.hello
- puts "hello world"
+ puts "hola mundo"
end
end
~~~
### git diff HEAD?查看已緩存的與未緩存的所有改動
如果你想一并查看已緩存的與未緩存的改動,可以執行?`git diff HEAD`?—— 也就是說你要看到的是工作目錄與上一次提交的更新的區別,無視緩存。 假設我們又改了些?`ruby.rb`?的內容,那緩存的與未緩存的改動我們就都有了。 以上三個?`diff`?命令的結果如下:
~~~
$ vim hello.rb
$ git diff
diff --git a/hello.rb b/hello.rb
index 4f40006..2ae9ba4 100644
--- a/hello.rb
+++ b/hello.rb
@@ -1,7 +1,7 @@
class HelloWorld
+ # says hello
def self.hello
puts "hola mundo"
end
end
$ git diff --cached
diff --git a/hello.rb b/hello.rb
index 2aabb6e..4f40006 100644
--- a/hello.rb
+++ b/hello.rb
@@ -1,7 +1,7 @@
class HelloWorld
def self.hello
- puts "hello world"
+ puts "hola mundo"
end
end
$ git diff HEAD
diff --git a/hello.rb b/hello.rb
index 2aabb6e..2ae9ba4 100644
--- a/hello.rb
+++ b/hello.rb
@@ -1,7 +1,8 @@
class HelloWorld
+ # says hello
def self.hello
- puts "hello world"
+ puts "hola mundo"
end
end
~~~
### git diff –stat?顯示摘要而非整個 diff
如果我們不想要看整個 diff 輸出,但是又想比?`git status`?詳細點, 就可以用?`--stat`?選項。該選項使它顯示摘要而非全文。上文示例在使用?`--stat`?選項時,輸出如下:
~~~
$ git status -s
MM hello.rb
$ git diff --stat
hello.rb | 1 +
1 files changed, 1 insertions(+), 0 deletions(-)
$ git diff --cached --stat
hello.rb | 2 +-
1 files changed, 1 insertions(+), 1 deletions(-)
$ git diff HEAD --stat
hello.rb | 3 ++-
1 files changed, 2 insertions(+), 1 deletions(-)
~~~
你還可以在上述命令后面制定一個目錄,從而只查看特定文件或子目錄的?`diff`?輸出。
> **簡而言之**, 執行?`git diff`?來查看執行?`git status`?的結果的詳細信息 —— 一行一行地顯示這些文件是如何被修改或寫入緩存的。