git diff 显示已写入缓存与已修改但尚未写入缓存的改动的区别
git diff
有两个主要的应用场景。我们将在此介绍其一, 在 检阅与对照 一章中,我们将介绍其二。 我们这里介绍的方式是用此命令描述已临时提交的或者已修改但尚未提交的改动。
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
的结果的详细信息 —— 一行一行地显示这些文件是如何被修改或写入缓存的。